diff --git a/api/client/builder/client.go b/api/client/builder/client.go index faff61d729..cf6b13327a 100644 --- a/api/client/builder/client.go +++ b/api/client/builder/client.go @@ -274,9 +274,6 @@ func non200Err(response *http.Response) error { if err != nil { body = "(Unable to read response body.)" } else { - if jsonErr := json.Unmarshal(bodyBytes, &errMessage); jsonErr != nil { - return errors.Wrap(jsonErr, "unable to read response body") - } body = "response body:\n" + string(bodyBytes) } msg := fmt.Sprintf("code=%d, url=%s, body=%s", response.StatusCode, response.Request.URL, body) @@ -285,13 +282,25 @@ func non200Err(response *http.Response) error { log.WithError(ErrNoContent).Debug(msg) return ErrNoContent case 400: + if jsonErr := json.Unmarshal(bodyBytes, &errMessage); jsonErr != nil { + return errors.Wrap(jsonErr, "unable to read response body") + } log.WithError(ErrBadRequest).Debug(msg) return errors.Wrap(ErrBadRequest, errMessage.Message) case 404: + if jsonErr := json.Unmarshal(bodyBytes, &errMessage); jsonErr != nil { + return errors.Wrap(jsonErr, "unable to read response body") + } log.WithError(ErrNotFound).Debug(msg) return errors.Wrap(ErrNotFound, errMessage.Message) - default: + case 500: + if jsonErr := json.Unmarshal(bodyBytes, &errMessage); jsonErr != nil { + return errors.Wrap(jsonErr, "unable to read response body") + } log.WithError(ErrNotOK).Debug(msg) return errors.Wrap(ErrNotOK, errMessage.Message) + default: + log.WithError(ErrNotOK).Debug(msg) + return errors.Wrap(ErrNotOK, fmt.Sprintf("unsupported error code: %d", response.StatusCode)) } } diff --git a/api/client/builder/client_test.go b/api/client/builder/client_test.go index 8210625d1d..9d711e0aaa 100644 --- a/api/client/builder/client_test.go +++ b/api/client/builder/client_test.go @@ -144,6 +144,23 @@ func TestClient_GetHeader(t *testing.T) { _, err := c.GetHeader(ctx, slot, bytesutil.ToBytes32(parentHash), bytesutil.ToBytes48(pubkey)) require.ErrorIs(t, err, ErrNotOK) + hc = &http.Client{ + Transport: roundtrip(func(r *http.Request) (*http.Response, error) { + require.Equal(t, expectedPath, r.URL.Path) + return &http.Response{ + StatusCode: http.StatusNoContent, + Body: io.NopCloser(bytes.NewBuffer([]byte("No header is available."))), + Request: r.Clone(ctx), + }, nil + }), + } + c = &Client{ + hc: hc, + baseURL: &url.URL{Host: "localhost:3500", Scheme: "http"}, + } + _, err = c.GetHeader(ctx, slot, bytesutil.ToBytes32(parentHash), bytesutil.ToBytes48(pubkey)) + require.ErrorIs(t, err, ErrNoContent) + hc = &http.Client{ Transport: roundtrip(func(r *http.Request) (*http.Response, error) { require.Equal(t, expectedPath, r.URL.Path)