Skip to content

Commit

Permalink
Merge pull request #98 from avinassh/error-history
Browse files Browse the repository at this point in the history
Add an example which shows err history
  • Loading branch information
JaSei authored Oct 12, 2023
2 parents abb9e3a + c51342a commit a9809a7
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions examples/errors_history_test.go
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)
}

0 comments on commit a9809a7

Please sign in to comment.