-
Notifications
You must be signed in to change notification settings - Fork 160
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #98 from avinassh/error-history
Add an example which shows err history
- Loading branch information
Showing
1 changed file
with
45 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
package retry_test | ||
|
||
import ( | ||
"fmt" | ||
"net/http" | ||
"net/http/httptest" | ||
"testing" | ||
|
||
"github.com/avast/retry-go/v4" | ||
"github.com/stretchr/testify/assert" | ||
) | ||
|
||
// TestErrorHistory shows an example of how to get all the previous errors when | ||
// retry.Do ends in success | ||
func TestErrorHistory(t *testing.T) { | ||
attempts := 3 // server succeeds after 3 attempts | ||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
if attempts > 0 { | ||
attempts-- | ||
w.WriteHeader(http.StatusBadGateway) | ||
return | ||
} | ||
w.WriteHeader(http.StatusOK) | ||
})) | ||
defer ts.Close() | ||
var allErrors []error | ||
err := retry.Do( | ||
func() error { | ||
resp, err := http.Get(ts.URL) | ||
if err != nil { | ||
return err | ||
} | ||
defer resp.Body.Close() | ||
if resp.StatusCode != 200 { | ||
return fmt.Errorf("failed HTTP - %d", resp.StatusCode) | ||
} | ||
return nil | ||
}, | ||
retry.OnRetry(func(n uint, err error) { | ||
allErrors = append(allErrors, err) | ||
}), | ||
) | ||
assert.NoError(t, err) | ||
assert.Len(t, allErrors, 3) | ||
} |