Skip to content

Commit eb82ae4

Browse files
committed
WrapError: wrap an error with fields to be logged by zap.Error
Related to uber-go/guide#179 Callsites that receive an error should either log, or return an error. However, if the callsite has additioanl context, the simplest option is to add it to the error, but it's then flattened into a string, losing the benefit of structured logging. This often results in callsites logging with additional fields, and returning an error that is likely to be logged again. `WrapError` provides a way for callsites to return an error that includes fields to be logged, which will be added to an `errorFields` key.
1 parent 845ca51 commit eb82ae4

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

fields_error.go

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package zap
2+
3+
import (
4+
"go.uber.org/zap/zapcore"
5+
)
6+
7+
type errorWithFields struct {
8+
err error
9+
fields []Field
10+
}
11+
12+
// WrapError returns an error that will log the provided fields if the error
13+
// is logged using `Error`.
14+
func WrapError(err error, fields ...Field) error {
15+
return &errorWithFields{
16+
err: err,
17+
fields: fields,
18+
}
19+
}
20+
21+
func (e errorWithFields) Unwrap() error {
22+
return e.err
23+
}
24+
25+
func (e errorWithFields) Error() string {
26+
return e.err.Error()
27+
}
28+
29+
func (e errorWithFields) MarshalLogObject(oe zapcore.ObjectEncoder) error {
30+
for _, f := range e.fields {
31+
f.AddTo(oe)
32+
}
33+
return nil
34+
}

zapcore/error.go

+7
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,13 @@ func encodeError(key string, err error, enc ObjectEncoder) (retErr error) {
7575
enc.AddString(key+"Verbose", verbose)
7676
}
7777
}
78+
79+
if errObj, ok := err.(ObjectMarshaler); ok {
80+
if err := enc.AddObject(key+"Fields", errObj); err != nil {
81+
return err
82+
}
83+
}
84+
7885
return nil
7986
}
8087

0 commit comments

Comments
 (0)