diff --git a/client.go b/client.go index 5779a8e1c..def2f7f58 100644 --- a/client.go +++ b/client.go @@ -209,12 +209,19 @@ func (c *Client) fullURL(suffix string, args ...any) string { } func (c *Client) handleErrorResp(resp *http.Response) error { + data, err := io.ReadAll(resp.Body) + if err != nil { + return &RequestError{ + HTTPStatusCode: resp.StatusCode, + Err: fmt.Errorf("read resp body failed: %w", err), + } + } var errRes ErrorResponse - err := json.NewDecoder(resp.Body).Decode(&errRes) + err = json.Unmarshal(data, &errRes) if err != nil || errRes.Error == nil { reqErr := &RequestError{ HTTPStatusCode: resp.StatusCode, - Err: err, + Err: fmt.Errorf("resp is not valid json: %s", string(data)), } if errRes.Error != nil { reqErr.Err = errRes.Error diff --git a/client_test.go b/client_test.go index 29d84edfa..d64ee46f9 100644 --- a/client_test.go +++ b/client_test.go @@ -158,6 +158,18 @@ func TestHandleErrorResp(t *testing.T) { }`)), expected: "error, status code: 503, message: ", }, + { + name: "500 invalid json", + httpCode: http.StatusInternalServerError, + body: bytes.NewReader([]byte(`dummy`)), + expected: "error, status code: 500, message: resp is not valid json: dummy", + }, + { + name: "500 error body", + httpCode: http.StatusInternalServerError, + body: &errorReader{err: errors.New("dummy")}, + expected: "error, status code: 500, message: read resp body failed: dummy", + }, } for _, tc := range testCases { @@ -171,12 +183,6 @@ func TestHandleErrorResp(t *testing.T) { t.Errorf("Unexpected error: %v , expected: %s", err, tc.expected) t.Fail() } - - e := &APIError{} - if !errors.As(err, &e) { - t.Errorf("(%s) Expected error to be of type APIError", tc.name) - t.Fail() - } }) } }