Skip to content

Commit 80130e3

Browse files
authored
Merge pull request #2 from mailgun/thrawn/tomap_last
ToMap and ToLogrus now use errors.Last()
2 parents f75ac50 + 446b539 commit 80130e3

2 files changed

Lines changed: 26 additions & 2 deletions

File tree

fields.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,7 @@ func ToMap(err error) map[string]interface{} {
177177

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

207207
// Find any errors with StackTrace information if available
208208
var stack callstack.HasStackTrace
209-
if errors.As(err, &stack) {
209+
if Last(err, &stack) {
210210
trace := stack.StackTrace()
211211
caller := callstack.GetLastFrame(trace)
212212
result["excFuncName"] = caller.Func

fields_test.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,30 @@ func TestNestedWithFields(t *testing.T) {
135135
})
136136
}
137137

138+
func TestToMapToLogrusFindsLastStackTrace(t *testing.T) {
139+
err := errors.New("this is an error")
140+
// Should report this line number for the stack in the chain
141+
err = errors.Wrap(err, "last")
142+
err = errors.Wrap(err, "second")
143+
err = errors.Wrap(err, "first")
144+
145+
t.Run("ToMap() finds the last stack in the chain", func(t *testing.T) {
146+
m := errors.ToMap(err)
147+
assert.NotNil(t, m)
148+
assert.Equal(t, 141, m["excLineNum"])
149+
})
150+
151+
t.Run("ToLogrus() finds the last stack in the chain", func(t *testing.T) {
152+
f := errors.ToLogrus(err)
153+
require.NotNil(t, f)
154+
b := bytes.Buffer{}
155+
logrus.SetOutput(&b)
156+
logrus.WithFields(f).Info("test logrus fields")
157+
logrus.SetOutput(os.Stdout)
158+
assert.Contains(t, b.String(), "excLineNum=141")
159+
})
160+
}
161+
138162
func TestWithFieldsFmtDirectives(t *testing.T) {
139163
t.Run("Wrap() with a message", func(t *testing.T) {
140164
err := errors.WithFields{"key1": "value1"}.Wrap(errors.New("error"), "shit happened")

0 commit comments

Comments
 (0)