-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors.go
56 lines (50 loc) · 1.2 KB
/
errors.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
package golib
import (
"bytes"
"fmt"
)
// MultiError is a helper type for combining multiple error values into one.
type MultiError []error
// NilOrError returns either nil, the only contained error, or the entire MultiError,
// depending on the number of contained errors.
func (err MultiError) NilOrError() error {
if len(err) == 0 {
return nil
} else if len(err) == 1 {
return err[0]
}
return err
}
// Add adds the given error to the MultiError, if it is not nil.
func (err *MultiError) Add(errOrNil error) {
if err != nil && errOrNil != nil {
*err = append(*err, errOrNil)
}
}
func (err *MultiError) AddMulti(possibleErrors ...interface{}) {
for _, possibleErr := range possibleErrors {
if trueError, isError := possibleErr.(error); isError {
err.Add(trueError)
}
}
}
// Error implements the error interface by printing all contained errors
// on a separate line.
func (err MultiError) Error() string {
switch len(err) {
case 0:
return "No error"
case 1:
return err[0].Error()
default:
var buf bytes.Buffer
fmt.Fprintln(&buf, "Multiple errors:")
for i, e := range err {
if i > 0 {
fmt.Fprintln(&buf)
}
fmt.Fprintf(&buf, "\t%v. %v", i+1, e)
}
return buf.String()
}
}