-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjoining.go
More file actions
96 lines (81 loc) · 1.95 KB
/
joining.go
File metadata and controls
96 lines (81 loc) · 1.95 KB
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
package errors
import "log/slog"
// Join returns an error that wraps the given errors with a stack trace
// at the point Join is called. Any nil error values are discarded.
// Join returns nil if errs contains no non-nil values.
// The error formats as the concatenation of the strings obtained
// by calling the Error method of each element of errs, with a newline
// between each string.
// If there is only one error in chain, then it's stack trace will be
// preserved if present.
func Join(errs ...error) error {
n := 0
for _, err := range errs {
if err != nil {
n++
}
}
if n == 0 {
return nil
}
if n == 1 {
for _, err := range errs {
if err != nil {
if isWrapper(err) {
return err
}
return &stacked{
wrapped: &wrapped{wrapped: err},
stack: newStack(0),
}
}
}
}
e := &joinError{errs: make([]error, 0, n)}
for _, err := range errs {
if err != nil {
e.errs = append(e.errs, err)
}
}
return &stacked{
wrapped: &wrapped{wrapped: e},
stack: newStack(0),
}
}
type joinError struct {
errs []error
}
func (e *joinError) Attrs() []slog.Attr {
return attrsFromErrors(e.errs)
}
func (e *joinError) Error() string {
var b []byte
for i, err := range e.errs {
if i > 0 {
b = append(b, '\n')
}
b = append(b, err.Error()...)
}
return string(b)
}
func (e *joinError) Unwrap() []error {
return e.errs
}
// attrsFromErrors recursively collects attributes from a slice of errors.
// It handles nested joined errors by recursively traversing them.
func attrsFromErrors(errs []error) []slog.Attr {
var attrs []slog.Attr
for _, err := range errs {
for w := err; w != nil; w = Unwrap(w) {
// Handle nested joined errors
if j, ok := w.(interface{ Unwrap() []error }); ok {
attrs = append(attrs, attrsFromErrors(j.Unwrap())...)
}
// Collect attributes from LoggableError
if loggable, ok := w.(LoggableError); ok {
attrs = append(attrs, loggable.Attrs()...)
}
}
}
return attrs
}