-
Notifications
You must be signed in to change notification settings - Fork 0
/
error.go
112 lines (94 loc) · 2 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
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
112
package errors
import (
"fmt"
"strings"
)
// Error is a lightweight drop-in replacement for standard errors package with stacktrace.
type Error struct {
Source string
Message error
Inner error
}
func NewError(source string, message, inner error) *Error {
return &Error{
Source: source,
Message: message,
Inner: inner,
}
}
// ErrorMessageOf returns the inner error message of the error
func ErrorMessageOf(err error) string {
var e *Error
if As(err, &e) {
return e.ErrorMessage()
}
return err.Error()
}
// Each iterates over all inner errors of Error
func (e *Error) Each(it func(err error) bool) {
if it == nil {
return
}
var current error = e
for current != nil {
if !it(current) {
break
}
var cast *Error
if As(current, &cast) {
current = cast.Unwrap()
} else {
current = nil
}
}
}
// StackTrace builds the stack trace of all inner errors of Error
func (e *Error) StackTrace() (list []string) {
list = make([]string, 0, 5)
defer func() {
// reverse
for i, j := 0, len(list)-1; i < j; i, j = i+1, j-1 {
list[i], list[j] = list[j], list[i]
}
}()
e.Each(func(err error) bool {
var e *Error
if As(err, &e) {
list = append(list, e.String())
} else {
list = append(list, err.Error())
}
return true
})
return
}
// String returns current error's message and source
func (e *Error) String() string {
if e.Message == nil {
return e.Source
}
return fmt.Sprintf("%v: %v", e.Source, e.Message)
}
// ErrorMessage returns the inner error message without source or stack trace
func (e *Error) ErrorMessage() (msg string) {
e.Each(func(err error) bool {
var e *Error
if As(err, &e) {
if e.Inner == nil {
msg = e.Message.Error()
return false
}
} else {
msg = err.Error()
return false
}
return true
})
return
}
// Error returns the stack trace of this error
func (e *Error) Error() string {
return strings.Join(e.StackTrace(), "\n")
}
// Unwrap returns the inner error
func (e *Error) Unwrap() error { return e.Inner }