Skip to content

Commit

Permalink
Allow to output nested goerr logging
Browse files Browse the repository at this point in the history
  • Loading branch information
m-mizutani committed Sep 10, 2023
1 parent 8b2933f commit 8e1f703
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
8 changes: 7 additions & 1 deletion errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,13 @@ func (x *Error) LogValue() slog.Value {
attrs = append(attrs, slog.Any("stacktrace", stacktrace))

if x.cause != nil {
attrs = append(attrs, slog.Any("cause", x.cause))
var errAttr slog.Attr
if lv, ok := x.cause.(slog.LogValuer); ok {
errAttr = slog.Any("cause", lv.LogValue())
} else {
errAttr = slog.Any("cause", x.cause)
}
attrs = append(attrs, errAttr)
}

return slog.GroupValue(attrs...)
Expand Down
14 changes: 13 additions & 1 deletion test/errors_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package main_test

import (
"bytes"
"fmt"
"log/slog"
"testing"

"github.com/m-mizutani/goerr"
Expand Down Expand Up @@ -44,7 +46,7 @@ func TestStackTrace(t *testing.T) {
require.Equal(t, 4, len(st))
assert.Equal(t, "github.com/m-mizutani/goerr/test_test.oops", st[0].Func)
assert.Regexp(t, `/goerr/test/errors_test\.go$`, st[0].File)
assert.Equal(t, 14, st[0].Line)
assert.Equal(t, 16, st[0].Line)
}

func TestMultileWrap(t *testing.T) {
Expand Down Expand Up @@ -101,3 +103,13 @@ func TestErrorString(t *testing.T) {
err := goerr.Wrap(goerr.Wrap(goerr.New("blue"), "orange"), "red")
assert.Equal(t, "red: orange: blue", err.Error())
}

func TestLoggingNestedError(t *testing.T) {
err1 := goerr.New("e1").With("color", "orange")
err2 := goerr.Wrap(err1, "e2").With("number", "five")
out := &bytes.Buffer{}
logger := slog.New(slog.NewJSONHandler(out, nil))
logger.Error("fail", slog.Any("error", err2))
assert.Contains(t, out.String(), `"number":"five"`)
assert.Contains(t, out.String(), `"color":"orange"`)
}

0 comments on commit 8e1f703

Please sign in to comment.