Skip to content

Commit

Permalink
Handle response error when body contains no valid json
Browse files Browse the repository at this point in the history
  • Loading branch information
Caviarion authored and Octrol committed Aug 17, 2023
1 parent a14bc10 commit c87f5ea
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 8 deletions.
11 changes: 9 additions & 2 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
18 changes: 12 additions & 6 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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()
}
})
}
}
Expand Down

0 comments on commit c87f5ea

Please sign in to comment.