This repository was archived by the owner on Aug 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmultierror.go
More file actions
92 lines (76 loc) · 1.68 KB
/
multierror.go
File metadata and controls
92 lines (76 loc) · 1.68 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
package multierror
import (
"fmt"
"io"
"sync"
)
// Builder contained errors and supports thread-safe addition of errors
type Builder struct {
mx sync.Mutex
errs multiError
}
// Add error (thread-safe), if err is nil, nothing will be added.
func (m *Builder) Add(err error) {
if err == nil {
return
}
m.mx.Lock()
m.errs = append(m.errs, err)
m.mx.Unlock()
}
// ToError returns one error contained many errors or nil if no errors
func (m *Builder) ToError() error {
if len(m.errs) == 0 {
return nil
}
return m.errs
}
// Errors return the underlying errors, if possible.
// An error value has a errors if it implements the following
// interface:
//
// type errors interface {
// Errors() []error
// }
//
// If the error does not implement Errors, the original error will
// be returned like []error{err}. If the error is nil, nil will be returned without further
// investigation.
func Errors(err error) []error {
type errors interface {
Errors() []error
}
if err == nil {
return nil
}
errs, ok := err.(errors)
if !ok {
return []error{err}
}
return errs.Errors()
}
type multiError []error
func (m multiError) Error() string {
return fmt.Sprintf("%s", m)
}
func (m multiError) Format(s fmt.State, verb rune) {
_, _ = io.WriteString(s, "MultiError:\n")
for k, v := range m {
switch verb {
case 'v':
if s.Flag('+') {
_, _ = fmt.Fprintf(s, "### %d ###\n", k+1)
_, _ = fmt.Fprintf(s, "%+v\n", v)
continue
}
_, _ = fmt.Fprintf(s, "# %d: ", k+1)
_, _ = fmt.Fprintf(s, "%v\n", v)
case 's', 'q':
_, _ = io.WriteString(s, v.Error())
_, _ = io.WriteString(s, "\n")
}
}
}
func (m multiError) Errors() []error {
return m
}