-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy patherror_details.go
88 lines (68 loc) · 1.87 KB
/
error_details.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
package errors
import (
"fmt"
)
// WithDetails annotates err with with arbitrary key-value pairs.
func WithDetails(err error, details ...interface{}) error {
if err == nil {
return nil
}
if len(details) == 0 {
return err
}
if len(details)%2 != 0 {
details = append(details, nil)
}
var w *withDetails
if !As(err, &w) {
w = &withDetails{
error: err,
}
err = w
}
// Limiting the capacity of the stored keyvals ensures that a new
// backing array is created if the slice must grow in With.
// Using the extra capacity without copying risks a data race.
d := append(w.details, details...) // nolint:gocritic
w.details = d[:len(d):len(d)]
return err
}
// GetDetails extracts the key-value pairs from err's chain.
func GetDetails(err error) []interface{} {
var details []interface{}
// Usually there is only one error with details (when using the WithDetails API),
// but errors themselves can also implement the details interface exposing their attributes.
UnwrapEach(err, func(err error) bool {
if derr, ok := err.(interface{ Details() []interface{} }); ok {
details = append(derr.Details(), details...)
}
return true
})
return details
}
// withDetails annotates an error with arbitrary key-value pairs.
type withDetails struct {
error error
details []interface{}
}
func (w *withDetails) Error() string { return w.error.Error() }
func (w *withDetails) Cause() error { return w.error }
func (w *withDetails) Unwrap() error { return w.error }
// Details returns the appended details.
func (w *withDetails) Details() []interface{} {
return w.details
}
func (w *withDetails) Format(s fmt.State, verb rune) {
switch verb {
case 'v':
if s.Flag('+') {
_, _ = fmt.Fprintf(s, "%+v", w.error)
return
}
_, _ = fmt.Fprintf(s, "%v", w.error)
case 's':
_, _ = fmt.Fprintf(s, "%s", w.error)
case 'q':
_, _ = fmt.Fprintf(s, "%q", w.error)
}
}