Skip to content

Commit

Permalink
Update xhttp retry
Browse files Browse the repository at this point in the history
  • Loading branch information
onanying committed Jan 12, 2024
1 parent 4b28abc commit 04837ff
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 8 deletions.
7 changes: 5 additions & 2 deletions src/xutil/xhttp/request_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,17 +79,20 @@ func TestDebugAndAbortRetry(t *testing.T) {
url := "https://aaaaa.com/"
retryIf := func(resp *xhttp.XResponse, err error) error {
if err != nil {
if count == 1 {
return err
}
return errors.Join(err, xhttp.ErrAbortRetry)
}
if resp.StatusCode != 200 {
return fmt.Errorf("invalid status_code: %d", resp.StatusCode)
}
return nil
}
resp, err := xhttp.Request("GET", url, xhttp.WithRetry(retryIf, retry.Attempts(2)))
resp, err := xhttp.Request("GET", url, xhttp.WithRetry(retryIf, retry.Attempts(3)))

a.Nil(resp)
a.NotNil(err)
a.Contains(err.Error(), "xhttp: abort further retries")
a.Equal(count, 1)
a.Equal(count, 2)
}
14 changes: 8 additions & 6 deletions src/xutil/xhttp/retry.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,17 @@ type RetryIfFunc func(*XResponse, error) error
func doRetry(opts *requestOptions, f func() (*XResponse, error)) (*XResponse, error) {
var resp *XResponse
var err error
var lastErr error
var errorLog []error
err = retry.Do(
func() error {
resp, err = f()
if opts.RetryIfFunc != nil {
err := opts.RetryIfFunc(resp, err)
if err != nil && errors.Is(err, ErrAbortRetry) {
lastErr = err
return nil
if err != nil {
errorLog = append(errorLog, err)
if errors.Is(err, ErrAbortRetry) {
return nil
}
}
return err
}
Expand All @@ -34,8 +36,8 @@ func doRetry(opts *requestOptions, f func() (*XResponse, error)) (*XResponse, er
if err != nil {
return nil, err
}
if lastErr != nil {
return nil, lastErr
if len(errorLog) > 0 {
return nil, errors.Join(errorLog...)
}
return resp, nil
}

0 comments on commit 04837ff

Please sign in to comment.