Skip to content
This repository has been archived by the owner on Dec 1, 2021. It is now read-only.

feat: Add a public method to determine if the error has been appended to the stack. #241

Closed
wants to merge 1 commit into from
Closed
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
21 changes: 21 additions & 0 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,27 @@ func New(message string) error {
}
}

// ExistStack return an error already with stack
// ExistStack will check all parent error
func ExistStack(err error) bool {
type stackTracer interface {
StackTrace() StackTrace
}
_, ok := err.(stackTracer)
if ok {
return true
}

type causer interface {
Cause() error
}
cause, ok := err.(causer)
if !ok {
return false
}
return ExistStack(cause.Cause())
}

// Errorf formats according to a format specifier and returns the string
// as a value that satisfies error.
// Errorf also records the stack trace at the point it was called.
Expand Down
20 changes: 20 additions & 0 deletions errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,26 @@ func TestNew(t *testing.T) {
}
}

func TestExistStack(t *testing.T) {
tests := []struct {
err error
want bool
}{
{io.EOF, false},
{New("read error"), true},
{Wrap(io.EOF, "read error"), true},
{WithMessage(io.EOF, "read error"), false},
{WithStack(io.EOF), true},
}

for _, tt := range tests {
got := ExistStack(tt.err)
if got != tt.want {
t.Errorf("ExistStack(%v): got: %v, want %v", tt.err, got, tt.want)
}
}
}

func TestWrapNil(t *testing.T) {
got := Wrap(nil, "no error")
if got != nil {
Expand Down