-
Notifications
You must be signed in to change notification settings - Fork 3
/
multierror.go
106 lines (94 loc) · 2.13 KB
/
multierror.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
97
98
99
100
101
102
103
104
105
106
// Example Use case for this library
//
// import "github.com/cloudfoundry/multierror"
//
// errors := multierror.MultiError{}
//
// err1 := FirstFuncThatReturnsError()
// err2 := SecondFuncThatReturnsError()
//
// errors.Add(err1)
// errors.Add(err2)
//
// //You can also add multierror structs and they will be flattened into one struct
// errors2 := multierror.MultiError()
// errors2.Add(err1)
// errors.Add(errors2)
//
// errors.Error()
package multierror
import (
"bytes"
"fmt"
"strings"
)
type MultiError struct {
Message string
Errors []*MultiError
isError bool
}
func NewMultiError(message string) *MultiError {
return &MultiError{
Message: message,
Errors: []*MultiError{},
isError: false,
}
}
func (m *MultiError) Add(e error) {
multierr, ok := e.(*MultiError)
if ok {
m.Errors = append(m.Errors, multierr)
} else {
leafError := NewMultiError(e.Error())
leafError.isError = true
m.Errors = append(m.Errors, leafError)
}
}
func (m *MultiError) isLeafNode() bool {
return m.isError && len(m.Errors) == 0
}
func (m *MultiError) Length() int {
if m.isLeafNode() {
return 1
}
var length int
for _, err := range m.Errors {
length += err.Length()
}
return length
}
func (m *MultiError) Error() string {
if m.Length() == 0 {
return "there were 0 errors"
}
return m.formatError(0)
}
func (m *MultiError) getMessage() string {
if m.isLeafNode() {
return fmt.Sprintf("* %s", m.Message)
}
var grammar string
if m.Length() == 1 {
grammar = "was 1 error"
} else {
grammar = fmt.Sprintf("were %d errors", m.Length())
}
msg := fmt.Sprintf("there %s", grammar)
if m.Message != "" {
msg = fmt.Sprintf("%s with '%s'", msg, m.Message)
}
return fmt.Sprintf("%s:", msg)
}
func (m *MultiError) formatError(indent int) string {
var buffer bytes.Buffer
for i := 0; i < indent; i++ {
buffer.WriteString(" ")
}
whitespace := buffer.String()
formattedMessage := strings.Replace(m.getMessage(), "\n", fmt.Sprintf("\n%s ", whitespace), -1)
buffer.WriteString(fmt.Sprintf("%s\n", formattedMessage))
for _, elem := range m.Errors {
buffer.WriteString(elem.formatError(indent + 1))
}
return buffer.String()
}