-
Notifications
You must be signed in to change notification settings - Fork 0
/
berr.go
111 lines (89 loc) · 1.95 KB
/
berr.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
107
108
109
110
111
package berr
import (
"errors"
"fmt"
"strings"
)
// New returns a Better Error with a interface
// compatible with the errors.New()
func New(text string) error {
return parse(errors.New(text))
}
// betterError is a struct to hold the error message and the cause of the error
type betterError struct {
fullMsg string
errMsg string
originalErr error
cause []error
}
// Error implements the error interface
func (p betterError) Error() string {
if len(p.cause) == 0 {
return p.errMsg
}
output := []string{
p.errMsg,
"",
"caused by:",
}
for l := 0; l < len(p.cause); l++ {
c := parse(p.cause[l])
output = append(output, fmt.Sprintf(" %2d: %s", l, c.errMsg))
}
output = append(output, collectStackTrace()...)
return strings.Join(output, "\n")
}
func (p betterError) Unwrap() []error {
// if the error is a join error, we want to join
// the formatted errors
if e, fromJoin := p.originalErr.(interface {
Unwrap() []error
}); fromJoin {
allErrors := e.Unwrap()
var out []error
for _, joinErr := range allErrors {
out = append(out, parse(joinErr))
}
return out
}
return []error{p.originalErr}
}
func parse(err error) betterError {
if err == nil {
return betterError{
errMsg: "",
originalErr: err,
}
}
return parseUnwrap(err)
}
// parseUnwrap is a helper function to convert an Unwrap error into a prettyError
func parseUnwrap(err error) betterError {
if _, supportsUnwrap := err.(interface {
Unwrap() error
}); !supportsUnwrap {
return betterError{
originalErr: err,
errMsg: err.Error(),
}
}
var causes []error
e := errors.Unwrap(err)
for {
if e == nil {
break
}
causes = append(causes, e)
e = errors.Unwrap(e)
}
errMsg := err.Error()
for _, c := range causes {
errMsg = strings.ReplaceAll(errMsg, fmt.Sprintf(": %s", c.Error()), "")
}
return betterError{
originalErr: err,
fullMsg: err.Error(),
errMsg: errMsg,
cause: causes,
}
}