-
Notifications
You must be signed in to change notification settings - Fork 82
/
errors.go
96 lines (85 loc) · 1.93 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
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
// errors is improved errors package.
package errors
import (
"bytes"
"fmt"
"strconv"
"github.com/andeya/goutil"
)
// New returns an error that formats as the given text.
func New(text string) error {
return &myerror{text}
}
// myerror is a trivial implementation of error.
type myerror struct {
s string
}
func (e *myerror) Error() string {
return e.s
}
// Errorf formats according to a format specifier and returns the string
// as a value that satisfies error.
func Errorf(format string, a ...interface{}) error {
return New(fmt.Sprintf(format, a...))
}
// Merge merges multiple errors.
func Merge(errs ...error) error {
return Append(nil, errs...)
}
// Append appends multiple errors to the error.
func Append(err error, errs ...error) error {
count := len(errs)
if count == 0 {
return err
}
var merged []error
if err != nil {
if e, ok := err.(*multiError); ok {
_count := len(e.errs)
merged = make([]error, _count, count+_count)
copy(merged, e.errs)
} else {
merged = make([]error, 1, count+1)
merged[0] = err
}
}
for _, err := range errs {
switch e := err.(type) {
case nil:
continue
case *multiError:
merged = append(merged, e.errs...)
default:
merged = append(merged, e)
}
}
if len(merged) == 0 {
return nil
}
return &multiError{
errs: merged,
}
}
// multiError merged multiple errors
type multiError struct {
errs []error
text string
}
// mergePrefix the multiple errors prefix
var mergePrefix = []byte("MultiError:\n")
// Error implement error interface.
func (m *multiError) Error() string {
if len(m.text) > 0 {
return m.text
}
var bText = make([]byte, len(mergePrefix), 56)
copy(bText, mergePrefix)
for i, err := range m.errs {
bText = append(bText, strconv.Itoa(i+1)...)
bText = append(bText, ". "...)
bText = append(bText, bytes.Trim(goutil.StringToBytes(err.Error()), "\n")...)
bText = append(bText, '\n')
}
m.text = goutil.BytesToString(bText)
return m.text
}