Skip to content
New issue

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

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

Already on GitHub? # to your account

feat(formaterror): add support for log valuer #9

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
6 changes: 5 additions & 1 deletion attributes.go
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
29 changes: 29 additions & 0 deletions attributes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading