Skip to content

Commit

Permalink
Fix errors.Wrap()/errors.Is() (#106)
Browse files Browse the repository at this point in the history
  • Loading branch information
vtopc authored Apr 15, 2022
1 parent 7038f61 commit 7f44ee5
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 1 deletion.
4 changes: 3 additions & 1 deletion errors/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,8 @@ type withStack struct {
*stack.CallStack
}

func (w *withStack) Cause() error { return w.error }
func (w *withStack) Cause() error { return w.error }
func (w *withStack) Unwrap() error { return w.error }
func (w *withStack) Context() map[string]interface{} {
if child, ok := w.error.(HasContext); ok {
return child.Context()
Expand Down Expand Up @@ -263,6 +264,7 @@ type withMessage struct {

func (w *withMessage) Error() string { return w.msg + ": " + w.cause.Error() }
func (w *withMessage) Cause() error { return w.cause }
func (w *withMessage) Unwrap() error { return w.cause }

func (w *withMessage) Format(s fmt.State, verb rune) {
switch verb {
Expand Down
1 change: 1 addition & 0 deletions errors/go113.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//go:build go1.13
// +build go1.13

package errors
Expand Down
59 changes: 59 additions & 0 deletions errors/go113_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
//go:build go1.13
// +build go1.13

package errors

import (
"fmt"
"testing"

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

func TestIs(t *testing.T) {
target := New("wrapped")

tests := []struct {
name string
target error
err error
}{
{
name: "holster_wrap",
target: target,
err: Wrap(target, "some reason"),
},
{
name: "holster_double_wrap",
target: target,
err: Wrap(Wrap(target, "reason 2"), "reason 1"),
},
{
name: "holster_triple_wrap",
target: target,
err: Wrap(Wrap(Wrap(target, "reason 3"), "reason 2"), "reason 1"),
},
{
name: "holster_triple_wrapf",
target: target,
err: Wrapf(Wrapf(Wrapf(target, "reason %d", 3), "reason %d", 2), "reason %d", 1),
},
{
name: "std_wrap",
target: target,
err: fmt.Errorf("some reason: %w", target),
},
{
name: "std_double_wrap",
target: target,
err: fmt.Errorf("reason 1: %w", fmt.Errorf("reason 2: %w", target)),
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert.True(t, Is(tt.err, tt.target))
assert.ErrorIs(t, tt.err, tt.target)
})
}
}

0 comments on commit 7f44ee5

Please sign in to comment.