Skip to content

Commit

Permalink
Test error marshal failed
Browse files Browse the repository at this point in the history
  • Loading branch information
prashantv committed Apr 19, 2023
1 parent 568f031 commit a81b924
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 10 deletions.
4 changes: 4 additions & 0 deletions wrap_error_test.go
Expand Up @@ -96,3 +96,7 @@ func TestWrapErrorDuplicateField(t *testing.T) {
},
}, enc.Fields)
}

func TestWrapErrorMarshalErr(t *testing.T) {

}
48 changes: 38 additions & 10 deletions zapcore/error_test.go
Expand Up @@ -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{}{
Expand All @@ -86,7 +96,8 @@ func TestErrorEncoding(t *testing.T) {
},
},
{
k: "err",
msg: "multierr",
k: "err",
iface: multierr.Combine(
errors.New("foo"),
errors.New("bar"),
Expand All @@ -102,6 +113,7 @@ func TestErrorEncoding(t *testing.T) {
},
},
{
msg: "nested error causes",
k: "e",
iface: customMultierr{},
want: map[string]interface{}{
Expand All @@ -119,14 +131,16 @@ func TestErrorEncoding(t *testing.T) {
},
},
{
msg: "simple error",
k: "k",
iface: fmt.Errorf("failed: %w", errors.New("egad")),
want: map[string]interface{}{
"k": "failed: egad",
},
},
{
k: "error",
msg: "multierr with causes",
k: "error",
iface: multierr.Combine(
fmt.Errorf("hello: %w",
multierr.Combine(errors.New("foo"), errors.New("bar")),
Expand All @@ -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)
})
}
}

Expand Down

0 comments on commit a81b924

Please sign in to comment.