Skip to content

Commit

Permalink
Merge pull request #1 from avast/log_of_err
Browse files Browse the repository at this point in the history
retry return error with log of all errors
  • Loading branch information
JaSei authored Sep 27, 2017
2 parents 8ea1249 + 73ec637 commit 370b1f8
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
17 changes: 16 additions & 1 deletion retry.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package retry

import (
"fmt"
"strings"
"time"
)

Expand Down Expand Up @@ -49,11 +50,14 @@ func RetryWithOpts(retryableFunction Retryable, opts RetryOpts) error {
func RetryCustom(retryableFunction Retryable, onRetryFunction OnRetry, opts RetryOpts) error {
var n uint

errorLog := make(errorLog, opts.tries)

for n < opts.tries {
err := retryableFunction()

if err != nil {
onRetryFunction(n, err)
errorLog[n] = err

delayTime := opts.delay * (1 << (n - 1))
time.Sleep((time.Duration)(delayTime) * opts.units)
Expand All @@ -64,5 +68,16 @@ func RetryCustom(retryableFunction Retryable, onRetryFunction OnRetry, opts Retr
n++
}

return fmt.Errorf("All (%d) retries fail", opts.tries)
return fmt.Errorf("All (%d) retries fail:\n%s", opts.tries, errorLog)
}

type errorLog []error

func (log errorLog) String() string {
logWithNumber := make([]string, len(log))
for i, l := range log {
logWithNumber[i] = fmt.Sprintf("#%d: %s", i+1, l.Error())
}

return strings.Join(logWithNumber, "\n")
}
13 changes: 13 additions & 0 deletions retry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,19 @@ func TestCustom(t *testing.T) {
NewRetryOpts().Units(time.Nanosecond),
)
assert.Error(t, err)

expectedErrorFormat := `All (10) retries fail:
#1: test
#2: test
#3: test
#4: test
#5: test
#6: test
#7: test
#8: test
#9: test
#10: test`
assert.Equal(t, expectedErrorFormat, err.Error(), "retry error format")
assert.Equal(t, uint(45), retrySum, "right count of retry")

retrySum = 0
Expand Down

0 comments on commit 370b1f8

Please sign in to comment.