From 8e1f703fb1fab54aafc2fc6308d15a11a418e777 Mon Sep 17 00:00:00 2001 From: Masayoshi Mizutani Date: Sun, 10 Sep 2023 10:53:23 +0900 Subject: [PATCH] Allow to output nested goerr logging --- errors.go | 8 +++++++- test/errors_test.go | 14 +++++++++++++- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/errors.go b/errors.go index bdcc788..3f38d4e 100644 --- a/errors.go +++ b/errors.go @@ -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...) diff --git a/test/errors_test.go b/test/errors_test.go index 40882bd..79cb985 100644 --- a/test/errors_test.go +++ b/test/errors_test.go @@ -1,7 +1,9 @@ package main_test import ( + "bytes" "fmt" + "log/slog" "testing" "github.com/m-mizutani/goerr" @@ -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) { @@ -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"`) +}