Skip to content

Commit

Permalink
Merge pull request #14 from odedva/master
Browse files Browse the repository at this point in the history
Added last error return from the retry function
  • Loading branch information
JaSei authored Jan 22, 2019
2 parents 48dfe71 + 13bfda1 commit 08d411b
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 10 deletions.
19 changes: 14 additions & 5 deletions options.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,25 @@ type OnRetryFunc func(n uint, err error)
type DelayTypeFunc func(n uint, config *config) time.Duration

type config struct {
attempts uint
delay time.Duration
onRetry OnRetryFunc
retryIf RetryIfFunc
delayType DelayTypeFunc
attempts uint
delay time.Duration
onRetry OnRetryFunc
retryIf RetryIfFunc
delayType DelayTypeFunc
lastErrorOnly bool
}

// Option represents an option for retry.
type Option func(*config)

// return the direct last error that came from the retried function
// default is false (return wrapped errors with everything)
func LastErrorOnly(lastErrorOnly bool) Option {
return func(c *config) {
c.lastErrorOnly = lastErrorOnly
}
}

// Attempts set count of retry
// default is 10
func Attempts(attempts uint) Option {
Expand Down
14 changes: 9 additions & 5 deletions retry.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,11 +78,12 @@ func Do(retryableFunc RetryableFunc, opts ...Option) error {

//default
config := &config{
attempts: 10,
delay: 100 * time.Millisecond,
onRetry: func(n uint, err error) {},
retryIf: func(err error) bool { return true },
delayType: BackOffDelay,
attempts: 10,
delay: 100 * time.Millisecond,
onRetry: func(n uint, err error) {},
retryIf: func(err error) bool { return true },
delayType: BackOffDelay,
lastErrorOnly: false,
}

//apply opts
Expand Down Expand Up @@ -117,6 +118,9 @@ func Do(retryableFunc RetryableFunc, opts ...Option) error {
n++
}

if config.lastErrorOnly {
return errorLog[n]
}
return errorLog
}

Expand Down
13 changes: 13 additions & 0 deletions retry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import (
"testing"
"time"

"fmt"

"github.com/stretchr/testify/assert"
)

Expand Down Expand Up @@ -92,3 +94,14 @@ func TestFixedSleep(t *testing.T) {
assert.Error(t, err)
assert.True(t, dur < 500*time.Millisecond, "3 times default retry is shorter then 500ms")
}

func TestLastErrorOnly(t *testing.T) {
var retrySum uint
err := Do(
func() error { return errors.New(fmt.Sprintf("%d", retrySum)) },
OnRetry(func(n uint, err error) { retrySum += 1 }),
Delay(time.Nanosecond),
LastErrorOnly(true),
)
assert.Equal(t, "9", err.Error())
}

0 comments on commit 08d411b

Please sign in to comment.