-
Notifications
You must be signed in to change notification settings - Fork 1
/
error.go
116 lines (96 loc) · 2.32 KB
/
error.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package log
import (
"errors"
"github.com/rs/zerolog"
"github.com/tehsphinx/errs"
)
// zerologErrorMarshalFunc implements custom error marshalling for the error types in the errs package.
func zerologErrorMarshalFunc(err error) interface{} {
var info errInfo
if !errors.As(err, &info) {
return err
}
zErr := newZerologErr(err)
zErr.evaluate()
if len(zErr.objects) == 0 {
return err
}
return zErr
}
// errInfo is used to identify errors that have additional information.
// stackError does not implement this interface as stack is handled differently by zerolog.
type errInfo interface {
error
HasErrInfo()
}
func newZerologErr(err error) zerologErr {
return zerologErr{error: err, objects: map[string]zerolog.LogObjectMarshaler{}}
}
type zerologErr struct {
error
objects map[string]zerolog.LogObjectMarshaler
}
func (s *zerologErr) evaluate() {
var (
fields fieldsT
)
defer func() {
if fields != nil {
s.objects["fields"] = fields
}
}()
nextErrs := []error{s.error}
for {
if len(nextErrs) == 0 {
return
}
curErrs := nextErrs
nextErrs = nil
for _, err := range curErrs {
//nolint:errorlint // This loop is a customized unwrap function.
//goland:noinspection GoTypeAssertionOnErrors
switch x := err.(type) {
case errs.FieldsError:
fields = fields.Join(x.GetFields())
default:
}
nextErrs = unwrap(err, nextErrs)
}
}
}
func unwrap(err error, unwrapped []error) []error {
//nolint:errorlint // This loop is a customized unwrap function.
switch x := err.(type) {
case interface{ Unwrap() error }:
if e := x.Unwrap(); e != nil {
unwrapped = append(unwrapped, e)
}
case interface{ Unwrap() []error }:
for _, e := range x.Unwrap() {
if e != nil {
unwrapped = append(unwrapped, e)
}
}
}
return unwrapped
}
// MarshalZerologObject implements zerolog.LogObjectMarshaler.
// It gathers all info the error chain contains and adds it to the log statement.
func (s zerologErr) MarshalZerologObject(event *zerolog.Event) {
event.Str("msg", s.Error())
for key, object := range s.objects {
event.Object(key, object)
}
}
type fieldsT map[string]interface{}
func (f fieldsT) Join(fields fieldsT) fieldsT {
for k, v := range f {
fields[k] = v
}
return fields
}
func (f fieldsT) MarshalZerologObject(e *zerolog.Event) {
for k, v := range f {
e.Any(k, v)
}
}