diff --git a/wrap_error_test.go b/wrap_error_test.go index a6f3b3409..bfa2454a4 100644 --- a/wrap_error_test.go +++ b/wrap_error_test.go @@ -96,3 +96,7 @@ func TestWrapErrorDuplicateField(t *testing.T) { }, }, enc.Fields) } + +func TestWrapErrorMarshalErr(t *testing.T) { + +} diff --git a/zapcore/error_test.go b/zapcore/error_test.go index a9d6870ce..be2fed9a1 100644 --- a/zapcore/error_test.go +++ b/zapcore/error_test.go @@ -68,14 +68,24 @@ func (e customMultierr) Errors() []error { } } +type customErrObject struct{} + +func (customErrObject) Error() string { return "custom err" } +func (customErrObject) MarshalLogObject(enc ObjectEncoder) error { + enc.AddInt("count", 1) + return errors.New("marshal failed") +} + func TestErrorEncoding(t *testing.T) { tests := []struct { + msg string k string t FieldType // defaults to ErrorType iface interface{} want map[string]interface{} }{ { + msg: "custom key and fields", k: "k", iface: errTooManyUsers(2), want: map[string]interface{}{ @@ -86,7 +96,8 @@ func TestErrorEncoding(t *testing.T) { }, }, { - k: "err", + msg: "multierr", + k: "err", iface: multierr.Combine( errors.New("foo"), errors.New("bar"), @@ -102,6 +113,7 @@ func TestErrorEncoding(t *testing.T) { }, }, { + msg: "nested error causes", k: "e", iface: customMultierr{}, want: map[string]interface{}{ @@ -119,6 +131,7 @@ func TestErrorEncoding(t *testing.T) { }, }, { + msg: "simple error", k: "k", iface: fmt.Errorf("failed: %w", errors.New("egad")), want: map[string]interface{}{ @@ -126,7 +139,8 @@ func TestErrorEncoding(t *testing.T) { }, }, { - k: "error", + msg: "multierr with causes", + k: "error", iface: multierr.Combine( fmt.Errorf("hello: %w", multierr.Combine(errors.New("foo"), errors.New("bar")), @@ -145,17 +159,31 @@ func TestErrorEncoding(t *testing.T) { }, }, }, + { + msg: "error fields marshal failed", + k: "error", + iface: customErrObject{}, + want: map[string]interface{}{ + "error": "custom err", + "errorError": "marshal failed", + "errorFields": map[string]interface{}{ + "count": 1, + }, + }, + }, } for _, tt := range tests { - if tt.t == UnknownType { - tt.t = ErrorType - } - - enc := NewMapObjectEncoder() - f := Field{Key: tt.k, Type: tt.t, Interface: tt.iface} - f.AddTo(enc) - assert.Equal(t, tt.want, enc.Fields, "Unexpected output from field %+v.", f) + t.Run(tt.msg, func(t *testing.T) { + if tt.t == UnknownType { + tt.t = ErrorType + } + + enc := NewMapObjectEncoder() + f := Field{Key: tt.k, Type: tt.t, Interface: tt.iface} + f.AddTo(enc) + assert.Equal(t, tt.want, enc.Fields, "Unexpected output from field %+v.", f) + }) } }