Skip to content

handle error response compatible #709

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

Closed
wants to merge 1 commit into from
Closed
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
35 changes: 25 additions & 10 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -251,21 +251,36 @@ func (c *Client) fullURL(suffix string, args ...any) string {
}

func (c *Client) handleErrorResp(resp *http.Response) error {
var errRes ErrorResponse
err := json.NewDecoder(resp.Body).Decode(&errRes)
if err != nil || errRes.Error == nil {
reqErr := &RequestError{
var errResp ErrorResponse
var compErrResp CompatibleErrorResponse

bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
return &RequestError{
HTTPStatusCode: resp.StatusCode,
Err: err,
}
if errRes.Error != nil {
reqErr.Err = errRes.Error
}
return reqErr
}

errRes.Error.HTTPStatusCode = resp.StatusCode
return errRes.Error
// Decode into ErrorResponse
// First attempt to decode into ErrorResponse
err = json.Unmarshal(bodyBytes, &errResp)
if err == nil && errResp.Error != nil {
errResp.Error.HTTPStatusCode = resp.StatusCode
return errResp.Error
}

// If the first decode didn't work or resulted in an empty Error, try CompatibleErrorResponse
err = json.Unmarshal(bodyBytes, &compErrResp)
if err == nil && compErrResp.APIError != nil {
compErrResp.HTTPStatusCode = resp.StatusCode
return compErrResp.APIError
}

return &RequestError{
HTTPStatusCode: resp.StatusCode,
Err: err,
}
}

func containsSubstr(s []string, e string) bool {
Expand Down
4 changes: 4 additions & 0 deletions error.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ type ErrorResponse struct {
Error *APIError `json:"error,omitempty"`
}

type CompatibleErrorResponse struct {
*APIError
}

func (e *APIError) Error() string {
if e.HTTPStatusCode > 0 {
return fmt.Sprintf("error, status code: %d, message: %s", e.HTTPStatusCode, e.Message)
Expand Down