Don't try to parse error responses with no body

HEAD requests for instance return no body while still having all the relevant Content-Type headers set, causing unnecessary parsing errors. This skips further parsing for all requests that don't have any body to begin with.

Signed-off-by: Markus Thömmes <markusthoemmes@me.com>
This commit is contained in:
Markus Thömmes 2024-03-20 11:44:24 +01:00
parent 3cb985cac0
commit e8820b2564
2 changed files with 23 additions and 1 deletions

View file

@ -46,8 +46,14 @@ func parseHTTPErrorResponse(resp *http.Response) error {
} }
statusCode := resp.StatusCode statusCode := resp.StatusCode
ctHeader := resp.Header.Get("Content-Type")
// A HEAD request for example validly does not contain any body, while
// still returning a JSON content-type.
if len(body) == 0 {
return makeError(statusCode, "")
}
ctHeader := resp.Header.Get("Content-Type")
if ctHeader == "" { if ctHeader == "" {
return makeError(statusCode, string(body)) return makeError(statusCode, string(body))
} }

View file

@ -57,6 +57,22 @@ func TestHandleHTTPResponseError401WithInvalidBody(t *testing.T) {
} }
} }
func TestHandleHTTPResponseError401WithNoBody(t *testing.T) {
json := ""
response := &http.Response{
Status: "401 Unauthorized",
StatusCode: 401,
Body: nopCloser{bytes.NewBufferString(json)},
Header: http.Header{"Content-Type": []string{"application/json; charset=utf-8"}},
}
err := HandleHTTPResponseError(response)
expectedMsg := "unauthorized: "
if !strings.Contains(err.Error(), expectedMsg) {
t.Errorf("Expected %q, got: %q", expectedMsg, err.Error())
}
}
func TestHandleHTTPResponseErrorExpectedStatusCode400ValidBody(t *testing.T) { func TestHandleHTTPResponseErrorExpectedStatusCode400ValidBody(t *testing.T) {
json := `{"errors":[{"code":"DIGEST_INVALID","message":"provided digest does not match"}]}` json := `{"errors":[{"code":"DIGEST_INVALID","message":"provided digest does not match"}]}`
response := &http.Response{ response := &http.Response{