forked from thatguystone/cog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors.go
87 lines (71 loc) · 1.74 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
package cog
import (
"bytes"
"errors"
"fmt"
)
// Errors holds a list of errors that can be combined into a single, line-
// delimited error message
type Errors struct {
prefix string
errs *[]error
}
func (es *Errors) init() {
if es.errs == nil {
es.errs = &[]error{}
}
}
// Empty checks to see if any errors have been added
func (es *Errors) Empty() bool {
return es.errs == nil || len(*es.errs) == 0
}
// Reset clears the state of Errors for use again
func (es *Errors) Reset() {
es.errs = nil
}
// Prefix returns an Errors for which all errors are prefixed with `prefix`.
func (es *Errors) Prefix(prefix string) *Errors {
es.init()
return &Errors{
prefix: es.prefix + prefix,
errs: es.errs,
}
}
// Add adds an error to the collector. It's safe to call this when err==nil.
func (es *Errors) Add(err error) {
es.Addf(err, "")
}
// Drain removes every error from the given channel until the channel closes
func (es *Errors) Drain(ch <-chan error) {
for err := range ch {
es.Add(err)
}
}
// Addf is like Add, but prefixes the error with the given format and args. If
// err==nil, this does nothing.
func (es *Errors) Addf(err error, format string, args ...interface{}) {
if err != nil {
es.init()
pfxf := "%s"
if es.prefix != "" {
pfxf = "%s: "
}
if format != "" {
pfxf += fmt.Sprintf(format+": ", args...)
}
err = fmt.Errorf(pfxf+"%v", es.prefix, err)
*es.errs = append(*es.errs, err)
}
}
// Error combines all previous errors into a single error, or returns nil if
// there were no errors.
func (es *Errors) Error() error {
if es.errs == nil || len(*es.errs) == 0 {
return nil
}
b := bytes.Buffer{}
for _, err := range *es.errs {
b.WriteString(fmt.Sprintf("%v\n", err))
}
return errors.New(b.String())
}