forked from hashicorp/consul-template
/
errorlist.go
72 lines (62 loc) · 1.72 KB
/
errorlist.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
package main
import (
"fmt"
"strings"
)
// ErrorList represents the combined error returned from an ErrorList
type ErrorList struct {
title string
errors []error
}
// Append adds a new error or errors onto the ErrorList
func (e *ErrorList) Append(errs ...error) {
e.errors = append(e.errors, errs...)
}
// Appendf adds a new error to the list, converting the given string to a proper
// error object.
func (e *ErrorList) Appendf(text string, args ...interface{}) {
e.errors = append(e.errors, fmt.Errorf(text, args...))
}
// ErrorList returns a formatted error with the title and each error as a bullet. If
// there are no errors in the list, ErrorList will return nil.
func (e *ErrorList) GetError() error {
if len(e.errors) == 0 {
return nil
}
return e
}
// Error implements the Error interface
func (e *ErrorList) Error() string {
buff := make([]string, 0)
for _, err := range e.errors {
switch err := err.(type) {
case *ErrorList:
buff = e.recursiveError(buff, err.errors, err.title)
default:
buff = append(buff, fmt.Sprintf("* %s", err))
}
}
return fmt.Sprintf("%d error(s) %s:\n%s", len(buff), e.title, strings.Join(buff, "\n"))
}
func (e *ErrorList) recursiveError(buff []string, errs []error, title string) []string {
for _, err := range errs {
switch err.(type) {
case *ErrorList:
typed, ok := err.(*ErrorList)
if !ok {
panic("could not convert error to ErrorList")
}
buff = e.recursiveError(buff, typed.errors, fmt.Sprintf("%s: %s", title, typed.title))
default:
buff = append(buff, fmt.Sprintf("* %s: %s", title, err))
}
}
return buff
}
// NewErrorList creates a new ErrorList
func NewErrorList(title string) *ErrorList {
return &ErrorList{
title: title,
errors: []error{},
}
}