/
add.go
57 lines (44 loc) · 914 Bytes
/
add.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
54
55
56
57
package errfields
type withField struct {
error
key string
value any
}
type withFields struct {
error
fields []kv
}
type kv struct {
key string
value any
}
func (w *withField) Unwrap() error { return w.error }
func (w *withField) ProvideLogFields(f func(key string, value any)) {
f(w.key, w.value)
}
func (w *withFields) Unwrap() error { return w.error }
func (w *withFields) ProvideLogFields(f func(key string, value any)) {
for i := len(w.fields) - 1; i >= 0; i-- {
field := w.fields[i]
f(field.key, field.value)
}
}
func Add(err error, key string, value any) error {
if w, ok := err.(withFields); ok {
w.fields = append(w.fields, kv{key, value})
return w
}
if w, ok := err.(withField); ok {
return &withFields{
error: w.error,
fields: []kv{
{w.key, w.value},
{key, value},
},
}
}
if err != nil {
return &withField{err, key, value}
}
return nil
}