Skip to content

Commit

Permalink
enhancement: include HTTP status text in error when response is unexp…
Browse files Browse the repository at this point in the history
…ected
  • Loading branch information
manicminer committed Mar 20, 2024
1 parent 4f82792 commit 0f5aa12
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions sdk/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -513,12 +513,23 @@ func (c *Client) Execute(ctx context.Context, req *Request) (*Response, error) {

// Determine whether response status is valid
if !containsStatusCode(req.ValidStatusCodes, resp.StatusCode) {
// The status code didn't match, but we also need to check the ValidStatusFUnc, if provided
// The status code didn't match, but we also need to check the ValidStatusFunc, if provided
// Note that the odata argument here is a best-effort and may be nil
if f := req.ValidStatusFunc; f != nil && f(resp.Response, resp.OData) {
return resp, nil
}

status := fmt.Sprintf("%d", resp.StatusCode)

// Prefer the status text returned in the response, but fall back to predefined status if absent
statusText := resp.Status
if statusText == "" {
statusText = http.StatusText(resp.StatusCode)
}
if statusText != "" {
status = fmt.Sprintf("%s (%s)", status, statusText)
}

// Determine suitable error text
var errText string
switch {
Expand All @@ -530,16 +541,16 @@ func (c *Client) Execute(ctx context.Context, req *Request) (*Response, error) {

respBody, err := io.ReadAll(resp.Body)
if err != nil {
return resp, fmt.Errorf("unexpected status %d, could not read response body", resp.StatusCode)
return resp, fmt.Errorf("unexpected status %s, could not read response body", status)
}
if len(respBody) == 0 {
return resp, fmt.Errorf("unexpected status %d received with no body", resp.StatusCode)
return resp, fmt.Errorf("unexpected status %s received with no body", status)
}

errText = fmt.Sprintf("response: %s", respBody)
}

return resp, fmt.Errorf("unexpected status %d with %s", resp.StatusCode, errText)
return resp, fmt.Errorf("unexpected status %s with %s", status, errText)
}

return resp, nil
Expand Down

0 comments on commit 0f5aa12

Please sign in to comment.