Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Go1.13 errors compat #9

Merged
merged 2 commits into from
Jul 14, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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")
}
}