Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Update Stringer panic check to look like stdlib #857

Merged
merged 1 commit into from
Aug 28, 2020
Merged
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
19 changes: 12 additions & 7 deletions zapcore/field.go
Original file line number Diff line number Diff line change
Expand Up @@ -205,18 +205,23 @@ func addFields(enc ObjectEncoder, fields []Field) {
}
}

func encodeStringer(key string, stringer interface{}, enc ObjectEncoder) (err error) {
func encodeStringer(key string, stringer interface{}, enc ObjectEncoder) (retErr error) {
// Try to capture panics (from nil references or otherwise) when calling
// the String() method, similar to https://golang.org/src/fmt/print.go#L540
defer func() {
if v := recover(); v != nil {
val := reflect.ValueOf(stringer)
if val.Kind() == reflect.Ptr && val.IsNil() {
if err := recover(); err != nil {
// If it's a nil pointer, just say "<nil>". The likeliest causes are a
// Stringer that fails to guard against nil or a nil pointer for a
// value receiver, and in either case, "<nil>" is a nice result.
if v := reflect.ValueOf(stringer); v.Kind() == reflect.Ptr && v.IsNil() {
enc.AddString(key, "<nil>")
} else {
err = fmt.Errorf("PANIC=%v", v)
return
}

retErr = fmt.Errorf("PANIC=%v", err)
}
}()

enc.AddString(key, stringer.(fmt.Stringer).String())
return
return nil
}