Skip to content

Commit a9809a7

Browse files
authored
Merge pull request avast#98 from avinassh/error-history
Add an example which shows err history
2 parents abb9e3a + c51342a commit a9809a7

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

examples/errors_history_test.go

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package retry_test
2+
3+
import (
4+
"fmt"
5+
"net/http"
6+
"net/http/httptest"
7+
"testing"
8+
9+
"github.com/avast/retry-go/v4"
10+
"github.com/stretchr/testify/assert"
11+
)
12+
13+
// TestErrorHistory shows an example of how to get all the previous errors when
14+
// retry.Do ends in success
15+
func TestErrorHistory(t *testing.T) {
16+
attempts := 3 // server succeeds after 3 attempts
17+
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
18+
if attempts > 0 {
19+
attempts--
20+
w.WriteHeader(http.StatusBadGateway)
21+
return
22+
}
23+
w.WriteHeader(http.StatusOK)
24+
}))
25+
defer ts.Close()
26+
var allErrors []error
27+
err := retry.Do(
28+
func() error {
29+
resp, err := http.Get(ts.URL)
30+
if err != nil {
31+
return err
32+
}
33+
defer resp.Body.Close()
34+
if resp.StatusCode != 200 {
35+
return fmt.Errorf("failed HTTP - %d", resp.StatusCode)
36+
}
37+
return nil
38+
},
39+
retry.OnRetry(func(n uint, err error) {
40+
allErrors = append(allErrors, err)
41+
}),
42+
)
43+
assert.NoError(t, err)
44+
assert.Len(t, allErrors, 3)
45+
}

0 commit comments

Comments
 (0)