-
Notifications
You must be signed in to change notification settings - Fork 4
/
errors.go
92 lines (80 loc) · 1.87 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
88
89
90
91
92
package util
import (
"fmt"
"strings"
"github.com/pkg/errors"
"github.com/samber/lo"
)
type stackTracer interface {
StackTrace() errors.StackTrace
}
type unwrappable interface {
Unwrap() error
}
type ErrorFrame struct {
Key string `json:"key" xml:"key"`
Loc string `json:"loc" xml:"loc"`
}
type ErrorDetail struct {
Type string `json:"type" xml:"type"`
Message string `json:"message" xml:"message"`
Stack []ErrorFrame `json:"stack,omitempty" xml:"stack,omitempty"`
StackTrace errors.StackTrace `json:"-" xml:"-"`
Cause *ErrorDetail `json:"cause,omitempty" xml:"cause,omitempty"`
}
func GetErrorDetail(e error, includeStack bool) *ErrorDetail {
var stack errors.StackTrace
var cause *ErrorDetail
if includeStack {
t, ok := e.(stackTracer)
if ok {
stack = t.StackTrace()
}
u, ok := e.(unwrappable)
if ok {
cause = GetErrorDetail(u.Unwrap(), includeStack)
}
}
msg := KeyError
if e != nil {
msg = e.Error()
}
return &ErrorDetail{
Type: KeyError,
Message: msg,
Stack: TraceDetail(stack),
StackTrace: stack,
Cause: cause,
}
}
func TraceDetail(trace errors.StackTrace) []ErrorFrame {
s := fmt.Sprintf("%+v", trace)
lines := StringSplitLines(s)
var validLines []string
lo.ForEach(lines, func(line string, _ int) {
if l := strings.TrimSpace(line); l != "" {
validLines = append(validLines, l)
}
})
var ret []ErrorFrame
for i := 0; i < len(validLines)-1; i += 2 {
f := ErrorFrame{Key: validLines[i], Loc: validLines[i+1]}
ret = append(ret, f)
}
return ret
}
func ErrorMerge(errs ...error) error {
errs = lo.Filter(errs, func(e error, _ int) bool {
return e != nil
})
switch len(errs) {
case 0:
return nil
case 1:
return errs[0]
}
msg := lo.Map(errs, func(e error, _ int) string {
return e.Error()
})
return errors.Wrapf(errs[0], strings.Join(msg, ", "))
}