diff --git a/middleware.go b/middleware.go index 6f866be8..9b19c463 100644 --- a/middleware.go +++ b/middleware.go @@ -357,7 +357,10 @@ func parseResponseBody(c *Client, res *Response) (err error) { } if res.Request.Error != nil { - err = Unmarshalc(c, ct, res.body, res.Request.Error) + unmarshalErr := Unmarshalc(c, ct, res.body, res.Request.Error) + if unmarshalErr != nil { + c.log.Warnf("Cannot unmarshal response body: %s", unmarshalErr) + } } } } diff --git a/request_test.go b/request_test.go index a385097c..e2fcdd93 100644 --- a/request_test.go +++ b/request_test.go @@ -1744,6 +1744,54 @@ func TestHostHeaderOverride(t *testing.T) { logResponse(t, resp) } +type HTTPErrorResponse struct { + Error string `json:"error,omitempty"` +} + +func TestNotFoundWithError(t *testing.T) { + var httpError HTTPErrorResponse + ts := createGetServer(t) + defer ts.Close() + + resp, err := dc().R(). + SetHeader(hdrContentTypeKey, "application/json"). + SetError(&httpError). + Get(ts.URL + "/not-found-with-error") + + assertError(t, err) + assertEqual(t, http.StatusNotFound, resp.StatusCode()) + assertEqual(t, "404 Not Found", resp.Status()) + assertNotNil(t, resp.Body()) + assertEqual(t, "{\"error\": \"Not found\"}", resp.String()) + assertNotNil(t, httpError) + assertEqual(t, "Not found", httpError.Error) + + logResponse(t, resp) +} + +func TestNotFoundWithoutError(t *testing.T) { + var httpError HTTPErrorResponse + + ts := createGetServer(t) + defer ts.Close() + + c := dc().outputLogTo(os.Stdout) + resp, err := c.R(). + SetError(&httpError). + SetHeader(hdrContentTypeKey, "application/json"). + Get(ts.URL + "/not-found-no-error") + + assertError(t, err) + assertEqual(t, http.StatusNotFound, resp.StatusCode()) + assertEqual(t, "404 Not Found", resp.Status()) + assertNotNil(t, resp.Body()) + assertEqual(t, 0, len(resp.Body())) + assertNotNil(t, httpError) + assertEqual(t, "", httpError.Error) + + logResponse(t, resp) +} + func TestPathParamURLInput(t *testing.T) { ts := createGetServer(t) defer ts.Close() diff --git a/resty_test.go b/resty_test.go index 76d56fd2..5fe41a94 100644 --- a/resty_test.go +++ b/resty_test.go @@ -113,6 +113,13 @@ func createGetServer(t *testing.T) *httptest.Server { _, _ = w.Write(body) case "/host-header": _, _ = w.Write([]byte(r.Host)) + case "/not-found-with-error": + w.Header().Set(hdrContentTypeKey, "application/json") + w.WriteHeader(http.StatusNotFound) + _, _ = w.Write([]byte(`{"error": "Not found"}`)) + case "/not-found-no-error": + w.Header().Set(hdrContentTypeKey, "application/json") + w.WriteHeader(http.StatusNotFound) } switch {