-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfields.go
53 lines (42 loc) · 1.14 KB
/
fields.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package cerrors
import (
"errors"
"fmt"
)
type withFields interface {
error
fmt.Formatter
Fields() map[string]interface{}
AddField(name string, value any)
AddFields(fields map[string]interface{})
}
// check interface implementation
var _ withFields = (*withFieldsError)(nil)
type withFieldsError struct {
cause error
fields map[string]interface{}
}
func newWithFields(err error) withFields {
if err == nil {
return nil
}
var fErr *withFieldsError
if errors.As(err, &fErr) {
return fErr
}
return &withFieldsError{cause: err, fields: make(map[string]interface{})}
}
func (w *withFieldsError) AddField(name string, value any) {
w.fields[name] = value
}
func (w *withFieldsError) AddFields(fields map[string]interface{}) {
for name, value := range fields {
w.fields[name] = value
}
}
func (w *withFieldsError) Error() string { return w.cause.Error() }
func (w *withFieldsError) Unwrap() error { return w.cause }
func (w *withFieldsError) Fields() map[string]interface{} { return w.fields }
func (w *withFieldsError) Format(f fmt.State, verb rune) {
fmt.Printf(fmt.FormatString(f, verb), w.cause)
}