Skip to content

Commit

Permalink
Fix error chain from pkgerrors (#552)
Browse files Browse the repository at this point in the history
  • Loading branch information
bastengao authored May 15, 2023
1 parent 8981d80 commit 4612e09
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 7 deletions.
23 changes: 20 additions & 3 deletions pkgerrors/stacktrace.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,32 @@ func frameField(f errors.Frame, s *state, c rune) string {

// MarshalStack implements pkg/errors stack trace marshaling.
//
// zerolog.ErrorStackMarshaler = MarshalStack
// zerolog.ErrorStackMarshaler = MarshalStack
func MarshalStack(err error) interface{} {
type stackTracer interface {
StackTrace() errors.StackTrace
}
sterr, ok := err.(stackTracer)
if !ok {
var sterr stackTracer
var ok bool
for err != nil {
sterr, ok = err.(stackTracer)
if ok {
break
}

u, ok := err.(interface {
Unwrap() error
})
if !ok {
return nil
}

err = u.Unwrap()
}
if sterr == nil {
return nil
}

st := sterr.StackTrace()
s := &state{}
out := make([]map[string]string, 0, len(st))
Expand Down
9 changes: 5 additions & 4 deletions pkgerrors/stacktrace_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package pkgerrors

import (
"bytes"
"fmt"
"regexp"
"testing"

Expand All @@ -17,11 +18,11 @@ func TestLogStack(t *testing.T) {
out := &bytes.Buffer{}
log := zerolog.New(out)

err := errors.Wrap(errors.New("error message"), "from error")
err := fmt.Errorf("from error: %w", errors.New("error message"))
log.Log().Stack().Err(err).Msg("")

got := out.String()
want := `\{"stack":\[\{"func":"TestLogStack","line":"20","source":"stacktrace_test.go"\},.*\],"error":"from error: error message"\}\n`
want := `\{"stack":\[\{"func":"TestLogStack","line":"21","source":"stacktrace_test.go"\},.*\],"error":"from error: error message"\}\n`
if ok, _ := regexp.MatchString(want, got); !ok {
t.Errorf("invalid log output:\ngot: %v\nwant: %v", got, want)
}
Expand All @@ -33,11 +34,11 @@ func TestLogStackFromContext(t *testing.T) {
out := &bytes.Buffer{}
log := zerolog.New(out).With().Stack().Logger() // calling Stack() on log context instead of event

err := errors.Wrap(errors.New("error message"), "from error")
err := fmt.Errorf("from error: %w", errors.New("error message"))
log.Log().Err(err).Msg("") // not explicitly calling Stack()

got := out.String()
want := `\{"stack":\[\{"func":"TestLogStackFromContext","line":"36","source":"stacktrace_test.go"\},.*\],"error":"from error: error message"\}\n`
want := `\{"stack":\[\{"func":"TestLogStackFromContext","line":"37","source":"stacktrace_test.go"\},.*\],"error":"from error: error message"\}\n`
if ok, _ := regexp.MatchString(want, got); !ok {
t.Errorf("invalid log output:\ngot: %v\nwant: %v", got, want)
}
Expand Down

0 comments on commit 4612e09

Please sign in to comment.