Skip to content

Commit

Permalink
Merge pull request #9 from hashicorp/go1.13-errors-compat
Browse files Browse the repository at this point in the history
Go1.13 errors compat
  • Loading branch information
dnephin authored Jul 14, 2020
2 parents 8a6fb52 + 96a78fc commit 7b00e5d
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
9 changes: 9 additions & 0 deletions errwrap.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ func Wrap(outer, inner error) error {
//
// format is the format of the error message. The string '{{err}}' will
// be replaced with the original error message.
//
// Deprecated: Use fmt.Errorf()
func Wrapf(format string, err error) error {
outerMsg := "<nil>"
if err != nil {
Expand Down Expand Up @@ -148,6 +150,9 @@ func Walk(err error, cb WalkFunc) {
for _, err := range e.WrappedErrors() {
Walk(err, cb)
}
case interface{ Unwrap() error }:
cb(err)
Walk(e.Unwrap(), cb)
default:
cb(err)
}
Expand All @@ -167,3 +172,7 @@ func (w *wrappedError) Error() string {
func (w *wrappedError) WrappedErrors() []error {
return []error{w.Outer, w.Inner}
}

func (w *wrappedError) Unwrap() error {
return w.Inner
}
25 changes: 25 additions & 0 deletions errwrap_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package errwrap

import (
"errors"
"fmt"
"testing"
)
Expand Down Expand Up @@ -41,6 +42,16 @@ func TestGetAll(t *testing.T) {
"foo",
1,
},
{
fmt.Errorf("foo: %w", fmt.Errorf("bar")),
"foo: bar",
1,
},
{
fmt.Errorf("foo: %w", fmt.Errorf("bar")),
"bar",
1,
},
}

for i, tc := range cases {
Expand Down Expand Up @@ -83,6 +94,11 @@ func TestGetAllType(t *testing.T) {
Wrapf("", nil),
0,
},
{
fmt.Errorf("one: %w", fmt.Errorf("two: %w", fmt.Errorf("three"))),
fmt.Errorf("%w", errors.New("")),
2,
},
}

for i, tc := range cases {
Expand All @@ -92,3 +108,12 @@ func TestGetAllType(t *testing.T) {
}
}
}

func TestWrappedError_IsCompatibleWithErrorsUnwrap(t *testing.T) {
inner := errors.New("inner error")
err := Wrap(errors.New("outer"), inner)
actual := errors.Unwrap(err)
if actual != inner {
t.Fatal("wrappedError did not unwrap to inner")
}
}

0 comments on commit 7b00e5d

Please sign in to comment.