Skip to content

Commit

Permalink
fix: correctly implement error interfaces on wrapped errors
Browse files Browse the repository at this point in the history
There were two problems:

* `ExpectedError` and `UnexpectedError` should unwrap themselves
* `ErrorSet` should support equivalency check when there's a single
error inside.

This fixes the scenario of matching an error from a retry loop (in case if
just a single error was encountered).

Signed-off-by: Andrey Smirnov <[email protected]>
  • Loading branch information
smira authored and talos-bot committed Nov 13, 2020
1 parent 752f081 commit 8c63d29
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
17 changes: 17 additions & 0 deletions retry/retry.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
package retry

import (
"errors"
"fmt"
"log"
"math/rand"
Expand Down Expand Up @@ -74,6 +75,14 @@ func (e *ErrorSet) Append(err error) bool {
return ok
}

// Is implements errors.Is.
func (e *ErrorSet) Is(err error) bool {
e.mu.Lock()
defer e.mu.Unlock()

return len(e.errs) == 1 && errors.Is(e.errs[0], err)
}

// TimeoutError represents a timeout error.
type TimeoutError struct{}

Expand All @@ -90,8 +99,16 @@ func IsTimeout(err error) bool {

type expectedError struct{ error }

func (e expectedError) Unwrap() error {
return e.error
}

type unexpectedError struct{ error }

func (e unexpectedError) Unwrap() error {
return e.error
}

type retryer struct {
duration time.Duration
options *Options
Expand Down
26 changes: 26 additions & 0 deletions retry/retry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,29 @@ func Test_retry(t *testing.T) {
})
}
}

func Test_errors(t *testing.T) {
e := errors.New("xyz")

if !errors.Is(ExpectedError(e), e) {
t.Fatal("expected error should wrap errors")
}

if !errors.Is(UnexpectedError(e), e) {
t.Fatal("unexpected error should wrap errors")
}

errSet := ErrorSet{}
errSet.Append(e)

if !errors.Is(&errSet, e) {
t.Fatal("error set should wrap errors")
}

errSet = ErrorSet{}
errSet.Append(UnexpectedError(e))

if !errors.Is(&errSet, e) {
t.Fatal("error set should wrap errors")
}
}

0 comments on commit 8c63d29

Please sign in to comment.