diff --git a/internal/codederror/codederror.go b/internal/codederror/codederror.go index 7f7ecb6..7d9c383 100644 --- a/internal/codederror/codederror.go +++ b/internal/codederror/codederror.go @@ -3,7 +3,9 @@ package codederror import ( + "fmt" "log/slog" + "reflect" "github.com/jgolang/errors" ) @@ -12,7 +14,9 @@ import ( // the chain depth-first, as errors.As does, and returns nil when it meets an // error that implements slog.LogValuer before a coded one: slog logs that // value instead, so an error that hides what it wraps keeps it hidden, even -// behind wrappers such as fmt.Errorf. The walk does not allocate. +// behind wrappers such as fmt.Errorf. A nil pointer ends its branch without +// calling Unwrap, which usually dereferences the receiver. The walk does not +// allocate. func Of(err error) *errors.Error { coded, _ := find(err) return coded @@ -28,6 +32,11 @@ func find(err error) (coded *errors.Error, found bool) { if coded, isCoded := err.(*errors.Error); isCoded { return coded, true } + if isNilPointer(err) { + // Unwrap on a nil receiver usually dereferences it; slog logs + // such an error as "", so the walk stops here. + return nil, false + } switch wrapper := err.(type) { case interface{ Unwrap() error }: err = wrapper.Unwrap() @@ -45,6 +54,27 @@ func find(err error) (coded *errors.Error, found bool) { return nil, false } +// Text returns err.Error() as slog writes an error that panics: "" when +// err is a nil pointer, "!PANIC: " otherwise, so logging never panics. +func Text(err error) (text string) { + defer func() { + if recovered := recover(); recovered != nil { + if isNilPointer(err) { + text = "" + return + } + text = fmt.Sprintf("!PANIC: %v", recovered) + } + }() + return err.Error() +} + +// isNilPointer reports whether err holds a nil pointer. +func isNilPointer(err error) bool { + value := reflect.ValueOf(err) + return value.Kind() == reflect.Pointer && value.IsNil() +} + // Group builds the group, under key, for coded: code, msg, debug and origin. // code and msg come from errors.CodeOf, which looks past errors whose code is // nil; they are left out when the chain has no code, so logging never panics @@ -58,7 +88,7 @@ func Group(key string, coded *errors.Error) slog.Attr { // so the context added by wrappers outside coded is not lost when the error // is not also the record's message. func GroupWithText(key string, err error, coded *errors.Error) slog.Attr { - attrs := append([]slog.Attr{slog.String("text", err.Error())}, fields(coded)...) + attrs := append([]slog.Attr{slog.String("text", Text(err))}, fields(coded)...) return slog.Attr{Key: key, Value: slog.GroupValue(attrs...)} } diff --git a/log.go b/log.go index 1ef40c4..ee6911a 100644 --- a/log.go +++ b/log.go @@ -89,7 +89,7 @@ func validateArgs(args ...any) (string, []any) { msg = v rest = args[1:] case error: - msg = v.Error() + msg = codederror.Text(v) // Clip so append never writes into spare capacity of the caller's slice. rest = slices.Clip(args[1:]) // The group has no text attribute: msg already carries v.Error(). diff --git a/typed_nil_error_test.go b/typed_nil_error_test.go new file mode 100644 index 0000000..754f86a --- /dev/null +++ b/typed_nil_error_test.go @@ -0,0 +1,81 @@ +package log + +import ( + "bytes" + stderrors "errors" + "fmt" + "log/slog" + "testing" +) + +// nilUnsafeError dereferences its receiver in Error and Unwrap, as many +// application error types do. +type nilUnsafeError struct{ inner error } + +func (e *nilUnsafeError) Error() string { return "wrapped: " + e.inner.Error() } +func (e *nilUnsafeError) Unwrap() error { return e.inner } + +func TestTypedNilWrapperErrorDoesNotPanic(t *testing.T) { + var typedNil *nilUnsafeError + tests := []struct { + name string + err error + want string + }{ + {name: "attribute", err: typedNil, want: ""}, + {name: "behind fmt.Errorf", err: fmt.Errorf("x: %w", typedNil), want: "x: "}, + // Join's Error calls the nil wrapper's Error on a non-nil receiver; + // slog writes this panic as text, and so does the logger. + {name: "behind errors.Join", err: stderrors.Join(typedNil), want: "!PANIC: runtime error: invalid memory address or nil pointer dereference"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var buf bytes.Buffer + instance := New(WithJSONHandler(&buf)) + + instance.Error("failed", "error", tt.err, slog.Group("req", slog.Any("error", tt.err))) + + record := decodeRecord(t, &buf) + if got := record["error"]; got != tt.want { + t.Fatalf("error = %v, want %q (line %s)", got, tt.want, buf.String()) + } + if got := errorAttrOf(record, "req", "error"); got != tt.want { + t.Fatalf("req.error = %v, want %q (line %s)", got, tt.want, buf.String()) + } + }) + } +} + +func TestPackageLevelTypedNilErrorAsMessageDoesNotPanic(t *testing.T) { + var typedNil *nilUnsafeError + + record := logErrorRecord(t, typedNil) + + if record["msg"] != "" || record["error"] != "" { + t.Fatalf("msg = %v, error = %v, want ", record["msg"], record["error"]) + } +} + +func TestTypedNilJoinedWithCodedErrorDoesNotPanic(t *testing.T) { + var typedNil *nilUnsafeError + joined := stderrors.Join(typedNil, newCodedError()) + const panicText = "!PANIC: runtime error: invalid memory address or nil pointer dereference" + + t.Run("attribute", func(t *testing.T) { + var buf bytes.Buffer + instance := New(WithJSONHandler(&buf)) + + instance.Error("failed", "error", joined) + + if got := errorAttrOf(decodeRecord(t, &buf), "error", "text"); got != panicText { + t.Fatalf("error.text = %v, want %q (line %s)", got, panicText, buf.String()) + } + }) + t.Run("package-level message", func(t *testing.T) { + record := logErrorRecord(t, joined) + + if record["msg"] != panicText { + t.Fatalf("msg = %v, want %q", record["msg"], panicText) + } + }) +}