Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ToMap and ToLogrus now use errors.Last() #2

Merged
merged 1 commit into from
Feb 2, 2023
Merged
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
4 changes: 2 additions & 2 deletions fields.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ func ToMap(err error) map[string]interface{} {

// Find any errors with StackTrace information if available
var stack callstack.HasStackTrace
if errors.As(err, &stack) {
if Last(err, &stack) {
trace := stack.StackTrace()
caller := callstack.GetLastFrame(trace)
result["excFuncName"] = caller.Func
Expand Down Expand Up @@ -206,7 +206,7 @@ func ToLogrus(err error) logrus.Fields {

// Find any errors with StackTrace information if available
var stack callstack.HasStackTrace
if errors.As(err, &stack) {
if Last(err, &stack) {
trace := stack.StackTrace()
caller := callstack.GetLastFrame(trace)
result["excFuncName"] = caller.Func
Expand Down
24 changes: 24 additions & 0 deletions fields_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,30 @@ func TestNestedWithFields(t *testing.T) {
})
}

func TestToMapToLogrusFindsLastStackTrace(t *testing.T) {
err := errors.New("this is an error")
// Should report this line number for the stack in the chain
err = errors.Wrap(err, "last")
err = errors.Wrap(err, "second")
err = errors.Wrap(err, "first")

t.Run("ToMap() finds the last stack in the chain", func(t *testing.T) {
m := errors.ToMap(err)
assert.NotNil(t, m)
assert.Equal(t, 141, m["excLineNum"])
})

t.Run("ToLogrus() finds the last stack in the chain", func(t *testing.T) {
f := errors.ToLogrus(err)
require.NotNil(t, f)
b := bytes.Buffer{}
logrus.SetOutput(&b)
logrus.WithFields(f).Info("test logrus fields")
logrus.SetOutput(os.Stdout)
assert.Contains(t, b.String(), "excLineNum=141")
})
}

func TestWithFieldsFmtDirectives(t *testing.T) {
t.Run("Wrap() with a message", func(t *testing.T) {
err := errors.WithFields{"key1": "value1"}.Wrap(errors.New("error"), "shit happened")
Expand Down