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

enhancement: include HTTP status text in error when response is unexpected #933

Merged
merged 1 commit into from
Mar 20, 2024
Merged
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
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
Loading