From 27450d4a8b1d7b09bddbeb961fc2c955a0f2d852 Mon Sep 17 00:00:00 2001 From: Samuel Berthe Date: Wed, 28 Aug 2024 19:21:51 +0200 Subject: [PATCH] feat(formaterror): add support for log valuer --- attributes.go | 6 +++++- attributes_test.go | 29 +++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/attributes.go b/attributes.go index 62d907a..04ed7f4 100644 --- a/attributes.go +++ b/attributes.go @@ -217,7 +217,11 @@ func FormatErrorKey(values map[string]any, errorKeys ...string) map[string]any { return values } -func FormatError(err error) map[string]any { +func FormatError(err error) any { + if e, ok := err.(slog.LogValuer); ok { + return e.LogValue() + } + return map[string]any{ "kind": reflect.TypeOf(err).String(), "error": err.Error(), diff --git a/attributes_test.go b/attributes_test.go index 3775e95..d841d68 100644 --- a/attributes_test.go +++ b/attributes_test.go @@ -373,6 +373,35 @@ func TestExtractError(t *testing.T) { is.EqualError(err, assert.AnError.Error()) } +type testError struct { +} + +func (t testError) Error() string { + return "test error" +} + +func (t testError) LogValue() slog.Value { + return slog.StringValue("an error") +} + +func TestFormatError(t *testing.T) { + t.Parallel() + is := assert.New(t) + + // not found + attrs := FormatError(assert.AnError) + is.Len(attrs, 3) + is.Equal(map[string]any{ + "kind": "*errors.errorString", + "error": assert.AnError.Error(), + "stack": nil, + }, attrs) + + // not found + attrs = FormatError(&testError{}) + is.Equal(slog.StringValue("an error"), attrs) +} + func TestRemoveEmptyAttrs(t *testing.T) { t.Parallel() is := assert.New(t)