-
Notifications
You must be signed in to change notification settings - Fork 5
/
error.go
63 lines (53 loc) · 1.18 KB
/
error.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
package stencil
import (
"bytes"
"fmt"
"reflect"
)
// Error collects information about failed operations
type Error struct {
Operations []*ErrorOperation
}
type ErrorOperation struct {
Operation string
Thing interface{}
Err error
}
func (self *ErrorOperation) Error() string {
if reflect.ValueOf(self.Thing).Kind() == reflect.Ptr {
return fmt.Sprintf("%s on %T: %s", self.Operation, self.Thing, self.Err)
} else {
return fmt.Sprintf("%s on %v: %s", self.Operation, self.Thing, self.Err)
}
}
func NewError() *Error {
return &Error{
Operations: []*ErrorOperation{},
}
}
func (self *Error) Add(operation string, thing interface{}, err error) *Error {
self.Operations = append(self.Operations, &ErrorOperation{
Operation: operation,
Thing: thing,
Err: err,
})
return self
}
func (self *Error) Error() string {
out := new(bytes.Buffer)
fmt.Fprintf(out, "[\n")
for i, operation := range self.Operations {
fmt.Fprintf(out, " %q", operation)
if i < len(self.Operations)-1 {
fmt.Fprintf(out, ",\n")
}
}
fmt.Fprintf(out, "]\n")
return out.String()
}
func (self *Error) ToError() error {
if len(self.Operations) == 0 {
return nil
}
return self
}