From 8c007bb76d0c3d0d0adb524f848cc5432c87a89d Mon Sep 17 00:00:00 2001 From: Masayoshi Mizutani Date: Mon, 8 Jul 2024 08:48:02 +0900 Subject: [PATCH 1/2] Fix nil pointer error in LogValue method --- errors.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/errors.go b/errors.go index 0ded8f0..d7b4cbd 100644 --- a/errors.go +++ b/errors.go @@ -206,6 +206,10 @@ func (x *Error) Values() map[string]any { } func (x *Error) LogValue() slog.Value { + if x == nil { + return slog.AnyValue(nil) + } + attrs := []slog.Attr{ slog.String("message", x.msg), } From 28c94fcee9fdcbf879db0c6566d1a10d6f1806b8 Mon Sep 17 00:00:00 2001 From: Masayoshi Mizutani Date: Mon, 8 Jul 2024 08:49:52 +0900 Subject: [PATCH 2/2] Add test for logging nil error in JSON format --- errors_test.go | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/errors_test.go b/errors_test.go index 3da7ee3..561c98b 100644 --- a/errors_test.go +++ b/errors_test.go @@ -167,3 +167,13 @@ func TestLoggingNestedError(t *testing.T) { t.Errorf("Expected log output to contain '\"color\":\"orange\"', got '%s'", out.String()) } } + +func TestLoggerWithNil(t *testing.T) { + out := &bytes.Buffer{} + var err *goerr.Error + logger := slog.New(slog.NewJSONHandler(out, nil)) + logger.Error("fail", slog.Any("error", err)) + if !strings.Contains(out.String(), `"error":null`) { + t.Errorf("Expected log output to contain '\"error\":null', got '%s'", out.String()) + } +}