From 0f5aa12534d71b34a56a8ac144b10979ef3fa348 Mon Sep 17 00:00:00 2001 From: Tom Bamford Date: Tue, 19 Mar 2024 19:05:36 +0000 Subject: [PATCH] enhancement: include HTTP status text in error when response is unexpected --- sdk/client/client.go | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/sdk/client/client.go b/sdk/client/client.go index 07ef77247bf..8cb50b45416 100644 --- a/sdk/client/client.go +++ b/sdk/client/client.go @@ -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 { @@ -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