Skip to content

Commit

Permalink
Failing first request and successfully retrying carries error from fi…
Browse files Browse the repository at this point in the history
…rst (#290)

* Failing the first request and successfully retrying carries error from first
* The error itself should be nil, not the assertion of it
* Clear Error on Success
  • Loading branch information
phillc authored and jeevatkm committed Dec 1, 2019
1 parent e29360f commit d7b9766
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
1 change: 1 addition & 0 deletions middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,7 @@ func parseResponseBody(c *Client, res *Response) (err error) {
if IsJSONType(ct) || IsXMLType(ct) {
// HTTP status code > 199 and < 300, considered as Result
if res.IsSuccess() {
res.Request.Error = nil
if res.Request.Result != nil {
err = Unmarshalc(c, ct, res.body, res.Request.Result)
return
Expand Down
10 changes: 10 additions & 0 deletions resty_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,16 @@ func createGetServer(t *testing.T) *httptest.Server {
_, _ = fmt.Fprintf(w, "%d", uint64(sinceLastRequest))
}
atomic.AddInt32(&attempt, 1)

case "/set-retry-error-recover":
w.Header().Set(hdrContentTypeKey, "application/json; charset=utf-8")
if atomic.LoadInt32(&attempt) == 0 {
w.WriteHeader(http.StatusTooManyRequests)
_, _ = w.Write([]byte(`{ "message": "too many" }`))
} else {
_, _ = w.Write([]byte(`{ "message": "hello" }`))
}
atomic.AddInt32(&attempt, 1)
case "/set-timeout-test-with-sequence":
seq := atomic.AddInt32(&sequence, 1)
time.Sleep(time.Second * 2)
Expand Down
31 changes: 31 additions & 0 deletions retry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -559,6 +559,37 @@ func TestClientRetryPost(t *testing.T) {
}
}

func TestClientRetryErrorRecover(t *testing.T) {
ts := createGetServer(t)
defer ts.Close()

c := dc().
SetRetryCount(2).
SetError(AuthError{}).
AddRetryCondition(
func(r *Response, _ error) bool {
err, ok := r.Error().(*AuthError)
retry := ok && r.StatusCode() == 429 && err.Message == "too many"
return retry
},
)

resp, err := c.R().
SetHeader(hdrContentTypeKey, "application/json; charset=utf-8").
SetJSONEscapeHTML(false).
SetResult(AuthSuccess{}).
Get(ts.URL + "/set-retry-error-recover")

assertError(t, err)

authSuccess := resp.Result().(*AuthSuccess)

assertEqual(t, http.StatusOK, resp.StatusCode())
assertEqual(t, "hello", authSuccess.Message)

assertNil(t, resp.Error())
}

func filler(*Response, error) bool {
return false
}

0 comments on commit d7b9766

Please sign in to comment.