metadata: wrap !200 error code in a typed err
This makes it easier to introspect later.
Fixes
@@ -300,8 +300,8 @@ func (c *Client) getETag(suffix string) (value, etag string, err error) {
// being stable anyway.
host = metadataIP
}
- url := "http://" + host + "/computeMetadata/v1/" + suffix
- req, _ := http.NewRequest("GET", url, nil)
+ u := "http://" + host + "/computeMetadata/v1/" + suffix
+ req, _ := http.NewRequest("GET", u, nil)
req.Header.Set("Metadata-Flavor", "Google")
req.Header.Set("User-Agent", userAgent)
res, err := c.hc.Do(req)
@@ -312,13 +312,13 @@ func (c *Client) getETag(suffix string) (value, etag string, err error) {
if res.StatusCode == http.StatusNotFound {
return "", "", NotDefinedError(suffix)
}
- if res.StatusCode != 200 {
- return "", "", fmt.Errorf("status code %d trying to fetch %s", res.StatusCode, url)
- }
all, err := ioutil.ReadAll(res.Body)
if err != nil {
return "", "", err
}
+ if res.StatusCode != 200 {
+ return "", "", &Error{Code: res.StatusCode, Message: string(all)}
+ }
return string(all), res.Header.Get("Etag"), nil
}
@@ -499,3 +499,15 @@ func (c *Client) Subscribe(suffix string, fn func(v string, ok bool) error) erro
}
}
}
+
+// Error contains an error response from the server.
+type Error struct {
+ // Code is the HTTP response status code.
+ Code int
+ // Message is the server response message.
+ Message string
+}
+
+func (e *Error) Error() string {
+ return fmt.Sprintf("compute: Received %d `%s`", e.Code, e.Message)
+}
