diff --git a/error.go b/error.go index f5eaee7..1cc8197 100644 --- a/error.go +++ b/error.go @@ -17,19 +17,15 @@ func (err *APIError) Error() string { return fmt.Sprintf("API request failed: %s", err.Message) } -func extractErrorMessage(r io.Reader) (errorMessage string) { +func extractErrorMessage(r io.Reader) (errorMessage string, err error) { bs, err := ioutil.ReadAll(r) if err != nil { - return + return "", err } var data struct{ Error struct{ Message string } } err = json.Unmarshal(bs, &data) - if err == nil { - errorMessage = data.Error.Message - } else { - var data struct{ Error string } - json.Unmarshal(bs, &data) - errorMessage = data.Error + if err != nil { + return "", err } - return + return data.Error.Message, nil } diff --git a/hosts_test.go b/hosts_test.go index da89104..51168fa 100644 --- a/hosts_test.go +++ b/hosts_test.go @@ -456,8 +456,8 @@ func TestRetireHost_NotFound(t *testing.T) { t.Error("request method should be POST but: ", req.Method) } - respJSON, _ := json.Marshal(map[string]string{ - "error": "Host Not Found.", + respJSON, _ := json.Marshal(map[string]map[string]string{ + "error": {"message": "Host Not Found."}, }) res.Header()["Content-Type"] = []string{"application/json"} @@ -544,8 +544,8 @@ func TestBulkRetireHosts_NotFound(t *testing.T) { t.Errorf("request IDs should be %+v but: %+v", expectIDs, data.IDs) } - respJSON, _ := json.Marshal(map[string]string{ - "error": "Hosts not found.", + respJSON, _ := json.Marshal(map[string]map[string]string{ + "error": {"message": "Hosts Not Found."}, }) res.Header()["Content-Type"] = []string{"application/json"} @@ -569,7 +569,7 @@ func TestBulkRetireHosts_NotFound(t *testing.T) { if expectStatus := http.StatusNotFound; apiErr.StatusCode != expectStatus { t.Errorf("api error StatusCode should be %d but got %d", expectStatus, apiErr.StatusCode) } - if expect := "API request failed: Hosts not found."; apiErr.Error() != expect { + if expect := "API request failed: Hosts Not Found."; apiErr.Error() != expect { t.Errorf("api error string should be \"%s\" but got \"%s\"", expect, apiErr.Error()) } } diff --git a/mackerel.go b/mackerel.go index 110c757..0063f1e 100644 --- a/mackerel.go +++ b/mackerel.go @@ -122,12 +122,12 @@ func (c *Client) Request(req *http.Request) (resp *http.Response, err error) { } } if resp.StatusCode < 200 || resp.StatusCode > 299 { - message := extractErrorMessage(resp.Body) + message, err := extractErrorMessage(resp.Body) defer resp.Body.Close() - if message != "" { - return nil, &APIError{StatusCode: resp.StatusCode, Message: message} + if err != nil { + return nil, &APIError{StatusCode: resp.StatusCode, Message: resp.Status} } - return nil, &APIError{StatusCode: resp.StatusCode, Message: resp.Status} + return nil, &APIError{StatusCode: resp.StatusCode, Message: message} } return resp, nil }