Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle response error when body contains no valid json #475

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading