Skip to content

Commit 74d2dee

Browse files
author
viktor
committed
handle error response compatible
1 parent 2446f08 commit 74d2dee

File tree

2 files changed

+29
-10
lines changed

2 files changed

+29
-10
lines changed

client.go

Lines changed: 25 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -251,21 +251,36 @@ func (c *Client) fullURL(suffix string, args ...any) string {
251251
}
252252

253253
func (c *Client) handleErrorResp(resp *http.Response) error {
254-
var errRes ErrorResponse
255-
err := json.NewDecoder(resp.Body).Decode(&errRes)
256-
if err != nil || errRes.Error == nil {
257-
reqErr := &RequestError{
254+
var errResp ErrorResponse
255+
var compErrResp CompatibleErrorResponse
256+
257+
bodyBytes, err := io.ReadAll(resp.Body)
258+
if err != nil {
259+
return &RequestError{
258260
HTTPStatusCode: resp.StatusCode,
259261
Err: err,
260262
}
261-
if errRes.Error != nil {
262-
reqErr.Err = errRes.Error
263-
}
264-
return reqErr
265263
}
266264

267-
errRes.Error.HTTPStatusCode = resp.StatusCode
268-
return errRes.Error
265+
// Decode into ErrorResponse
266+
// First attempt to decode into ErrorResponse
267+
err = json.Unmarshal(bodyBytes, &errResp)
268+
if err == nil && errResp.Error != nil {
269+
errResp.Error.HTTPStatusCode = resp.StatusCode
270+
return errResp.Error
271+
}
272+
273+
// If the first decode didn't work or resulted in an empty Error, try CompatibleErrorResponse
274+
err = json.Unmarshal(bodyBytes, &compErrResp)
275+
if err == nil && compErrResp.APIError != nil {
276+
compErrResp.HTTPStatusCode = resp.StatusCode
277+
return compErrResp.APIError
278+
}
279+
280+
return &RequestError{
281+
HTTPStatusCode: resp.StatusCode,
282+
Err: err,
283+
}
269284
}
270285

271286
func containsSubstr(s []string, e string) bool {

error.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,10 @@ type ErrorResponse struct {
3333
Error *APIError `json:"error,omitempty"`
3434
}
3535

36+
type CompatibleErrorResponse struct {
37+
*APIError
38+
}
39+
3640
func (e *APIError) Error() string {
3741
if e.HTTPStatusCode > 0 {
3842
return fmt.Sprintf("error, status code: %d, message: %s", e.HTTPStatusCode, e.Message)

0 commit comments

Comments
 (0)