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

get first stack trace info. #195

Closed
wants to merge 6 commits 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
32 changes: 32 additions & 0 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -280,3 +280,35 @@ func Cause(err error) error {
}
return err
}

// Stack returns the earliest/deepest StackTrace attached to any of
// the errors in the chain of Causes. If the error does not implement
// Cause, the original error will be returned. If the error is nil,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you mean "the stacktrace from the original error will be returned"?

// nil will be returned without further investigation.
func Stack(err error) StackTrace {
type causer interface {
Cause() error
}

type stackTracer interface {
StackTrace() StackTrace
}

var topStackInfo StackTrace

for {
stackErr, ok := err.(stackTracer)
if ok {
topStackInfo = stackErr.StackTrace()
}

causer, ok := err.(causer)
if !ok {
break
}

err = causer.Cause()
}

return topStackInfo
}
60 changes: 60 additions & 0 deletions errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,66 @@ func TestCause(t *testing.T) {
}
}

func printStack(tracer StackTrace) string {
var logInfo string
for _, f := range tracer {
logInfo += fmt.Sprintf("%+s:%d ", f, f)
}
return logInfo
}

func TestStack(t *testing.T) {
type stackTracer interface {
StackTrace() StackTrace
}

x := New("error")
y := x.(stackTracer).StackTrace()

tests := []struct {
err error
want StackTrace
}{
{
err: nil,
want: nil,
}, {
err: (error)(nil),
want: nil,
}, {
err: io.EOF,
want: nil,
}, {
err: WithStack(x),
want: y,
}, {
err: WithStack(WithStack(x)),
want: y,
}, {
err: Wrap(WithStack(WithStack(x)), "test wrap"),
want: y,
}, {
err: Cause(Wrap(WithStack(WithStack(x)), "test wrap")),
want: y,
},
}

for i, tt := range tests {
got := Stack(tt.err)
if got == nil || tt.want == nil {
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("test %d: got %#v, want %#v", i+1, got, tt.want)
}

continue
}

if !reflect.DeepEqual(printStack(got), printStack(tt.want)) {
t.Errorf("test %d: got %#v, want %#v", i+1, printStack(got), printStack(tt.want))
}
}
}

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