Skip to content

Commit

Permalink
fix: parseResponseBody overrides original error code in case of unmar…
Browse files Browse the repository at this point in the history
…shal (#674)
  • Loading branch information
dmartinol committed Sep 19, 2023
1 parent d9bcfaa commit ca02e3e
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 1 deletion.
5 changes: 4 additions & 1 deletion middleware.go
Expand Up @@ -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)
}
}
}
}
Expand Down
48 changes: 48 additions & 0 deletions request_test.go
Expand Up @@ -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()
Expand Down
7 changes: 7 additions & 0 deletions resty_test.go
Expand Up @@ -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 {
Expand Down

0 comments on commit ca02e3e

Please sign in to comment.