Skip to content

Commit

Permalink
add Cause function
Browse files Browse the repository at this point in the history
find the root error
  • Loading branch information
ericuni committed Apr 21, 2024
1 parent d110058 commit dad676c
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
16 changes: 16 additions & 0 deletions error.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package errorx

import (
"errors"
"fmt"
)

Expand All @@ -24,3 +25,18 @@ func Tracef(err error, format string, args ...interface{}) error {
}
return fmt.Errorf("%s %s\n%w", getLocation(), fmt.Sprintf(format, args...), err)
}

func Cause(err error) error {
if err == nil {
return nil
}

for {
next := errors.Unwrap(err)
if next == nil {
return err
}

err = next
}
}
46 changes: 46 additions & 0 deletions error_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ func TestTrace(t *testing.T) {
assert.True(errors.Is(err, errNotFound))
t.Logf("\n%+v", err)

got := errors.Unwrap(err)
t.Log(got)

errNone := errors.New("none")
assert.False(errors.Is(err, errNone))
})
Expand All @@ -41,6 +44,49 @@ func TestTrace(t *testing.T) {
})
}

func TestCause(t *testing.T) {
assert := assert.New(t)

tds := []struct {
name string
err error
want error
}{
{
name: "nil",
err: nil,
want: nil,
},
{
name: "standard error",
err: errors.New("err1"),
want: errors.New("err1"),
},
{
name: "trace err",
err: Trace(errors.New("err1")),
want: errors.New("err1"),
},
{
name: "more trace err",
err: Trace(Trace(errors.New("err1"))),
want: errors.New("err1"),
},
{
name: "tracef err",
err: Tracef(errors.New("err1"), "description"),
want: errors.New("err1"),
},
}

for _, td := range tds {
t.Run(td.name, func(t *testing.T) {
got := Cause(td.err)
assert.Equal(td.want, got)
})
}
}

type PointerError struct {
code int32
msg string
Expand Down

0 comments on commit dad676c

Please sign in to comment.