Skip to content

Commit

Permalink
introduce MarkTemporary
Browse files Browse the repository at this point in the history
  • Loading branch information
shogo82148 committed Jun 18, 2024
1 parent 3b50794 commit 0163529
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
24 changes: 24 additions & 0 deletions retry.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,9 @@ func (p *Policy) Do(ctx context.Context, f func() error) error {
if err := retrier.err; err != nil {
return err
}
if err, ok := err.(*temporaryError); ok {
return err.error
}
return err
}

Expand Down Expand Up @@ -118,6 +121,27 @@ func MarkPermanent(err error) error {
return &permanentError{err}
}

type temporaryError struct {
error
}

// implements interface{ Temporary() bool }
// Inspecting errors https://dave.cheney.net/2014/12/24/inspecting-errors
func (e *temporaryError) Temporary() bool {
return true
}

// Unwrap implements errors.Wrapper.
func (e *temporaryError) Unwrap() error {
return e.error
}

// MarkTemporary marks err as a temporary error.
// It returns the error that implements interface{ Temporary() bool } and Temporary() returns true.
func MarkTemporary(err error) error {
return &temporaryError{err}
}

// Continue returns whether retrying should be continued.
func (r *Retrier) Continue() bool {
r.count++
Expand Down
23 changes: 22 additions & 1 deletion retry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -266,13 +266,34 @@ func TestDo_Success(t *testing.T) {

func TestDo_MarkPermanent(t *testing.T) {
permanentErr := errors.New("permanent error")
policy := &Policy{}
policy := &Policy{MaxCount: 10}
count := 0
err := policy.Do(context.Background(), func() error {
count++
return MarkPermanent(permanentErr)
})
if err != permanentErr {
t.Errorf("want error is %#v, got %#v", err, permanentErr)
}
if count != 1 {
t.Errorf("want %d, got %d", 1, count)
}
}

func TestDo_MarkTemporary(t *testing.T) {
temporaryErr := errors.New("temporary error")
policy := &Policy{MaxCount: 10}
count := 0
err := policy.Do(context.Background(), func() error {
count++
return MarkTemporary(temporaryErr)
})
if err != temporaryErr {
t.Errorf("want error is %#v, got %#v", err, temporaryErr)
}
if count != 10 {
t.Errorf("want %d, got %d", 10, count)
}
}

type customError bool
Expand Down

0 comments on commit 0163529

Please sign in to comment.