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

Show "<nil>" for nil Stringer. #854

Merged
merged 1 commit into from Aug 28, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 6 additions & 1 deletion zapcore/field.go
Expand Up @@ -208,7 +208,12 @@ func addFields(enc ObjectEncoder, fields []Field) {
func encodeStringer(key string, stringer interface{}, enc ObjectEncoder) (err error) {
defer func() {
if v := recover(); v != nil {
err = fmt.Errorf("PANIC=%v", v)
val := reflect.ValueOf(stringer)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This block looks very similar to the logic in the fmt package uses to determine if nil should be used,
https://golang.org/src/fmt/print.go#L540

Should we reference this?

Copy link
Collaborator

@abhinav abhinav Aug 28, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
val := reflect.ValueOf(stringer)
// See also https://golang.org/src/fmt/print.go#L540.
val := reflect.ValueOf(stringer)

if val.Kind() == reflect.Ptr && val.IsNil() {
enc.AddString(key, "<nil>")
} else {
err = fmt.Errorf("PANIC=%v", v)
}
}
}()

Expand Down
3 changes: 2 additions & 1 deletion zapcore/field_test.go
Expand Up @@ -102,7 +102,6 @@ func TestFieldAddingError(t *testing.T) {
{t: StringerType, iface: &obj{1}, want: empty, err: "PANIC=panic with string"},
{t: StringerType, iface: &obj{2}, want: empty, err: "PANIC=panic with error"},
{t: StringerType, iface: &obj{3}, want: empty, err: "PANIC=<nil>"},
{t: StringerType, iface: (*url.URL)(nil), want: empty, err: "PANIC=runtime error: invalid memory address or nil pointer dereference"},
}
for _, tt := range tests {
f := Field{Key: "k", Interface: tt.iface, Type: tt.t}
Expand Down Expand Up @@ -149,6 +148,8 @@ func TestFields(t *testing.T) {
{t: StringerType, iface: &obj{}, want: "obj"},
{t: StringerType, iface: (*obj)(nil), want: "nil obj"},
{t: SkipType, want: interface{}(nil)},
{t: StringerType, iface: (*url.URL)(nil), want: "<nil>"},
{t: StringerType, iface: (*users)(nil), want: "<nil>"},
}

for _, tt := range tests {
Expand Down