Skip to content

Commit

Permalink
Fix panic on <nil> values (#88)
Browse files Browse the repository at this point in the history
* added test

* added recover

* dropped testcase

---------

Co-authored-by: lmittmann <[email protected]>
  • Loading branch information
lmittmann and lmittmann authored Jan 28, 2025
1 parent cdb3c00 commit 2f95434
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
21 changes: 20 additions & 1 deletion handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ import (
"io"
"log/slog"
"path/filepath"
"reflect"
"runtime"
"strconv"
"strings"
Expand Down Expand Up @@ -404,6 +405,24 @@ func (h *handler) appendValue(buf *buffer, v slog.Value, quote bool) {
case slog.KindTime:
appendString(buf, v.Time().String(), quote, !h.noColor)
case slog.KindAny:
defer func() {
// Copied from log/slog/handler.go.
if r := recover(); r != nil {
// If it panics with a nil pointer, the most likely cases are
// an encoding.TextMarshaler or error fails to guard against nil,
// in which case "<nil>" seems to be the feasible choice.
//
// Adapted from the code in fmt/print.go.
if v := reflect.ValueOf(v.Any()); v.Kind() == reflect.Pointer && v.IsNil() {
appendString(buf, "<nil>", false, false)
return
}

// Otherwise just print the original panic message.
appendString(buf, fmt.Sprintf("!PANIC: %v", r), true, !h.noColor)
}
}()

switch cv := v.Any().(type) {
case slog.Level:
h.appendLevel(buf, cv)
Expand All @@ -416,7 +435,7 @@ func (h *handler) appendValue(buf *buffer, v slog.Value, quote bool) {
case *slog.Source:
h.appendSource(buf, cv)
default:
appendString(buf, fmt.Sprintf("%+v", v.Any()), quote, !h.noColor)
appendString(buf, fmt.Sprintf("%+v", cv), quote, !h.noColor)
}
}
}
Expand Down
7 changes: 7 additions & 0 deletions handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,13 @@ func TestHandler(t *testing.T) {
},
Want: `Nov 10 23:00:00.000 ERR test error=fail`,
},
{ // https://github.com/lmittmann/tint/issues/85
F: func(l *slog.Logger) {
var t *time.Time
l.Info("test", "time", t)
},
Want: `Nov 10 23:00:00.000 INF test time=<nil>`,
},
}

for i, test := range tests {
Expand Down

0 comments on commit 2f95434

Please sign in to comment.