-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror.go
More file actions
132 lines (104 loc) · 2.17 KB
/
error.go
File metadata and controls
132 lines (104 loc) · 2.17 KB
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package errx
import (
"errors"
"fmt"
"slices"
"strings"
"github.com/reedchan7/errx/errcode"
)
var _ error = (*xerr)(nil)
type xerr struct {
err error
code errcode.Code
msg string
stacktrace *stacktrace
}
func newError(err error, code errcode.Code, format string, args ...any) *xerr {
return &xerr{
err: err,
code: code,
msg: fmt.Sprintf(format, args...),
stacktrace: newStacktrace(),
}
}
// Error returns the error message, without context.
func (e *xerr) Error() string {
if e.err != nil {
if e.msg == "" {
return e.err.Error()
}
return fmt.Sprintf("%s: %s", e.msg, e.err.Error())
}
return e.msg
}
func (e *xerr) Code() errcode.Code {
return e.code
}
func (e *xerr) Cause() error {
return e.err
}
func (e *xerr) Unwrap() error {
return e.err
}
// Format implements fmt.Formatter.
// If the format is "%+v", then the details of the error are included.
// Otherwise, using "%v", just the summary is included.
func (e *xerr) Format(s fmt.State, verb rune) {
if verb == 'v' && s.Flag('+') {
fmt.Fprint(s, e.formatVerbose())
} else {
fmt.Fprint(s, e.formatSummary())
}
}
func (e *xerr) formatVerbose() string {
return e.formatStacktrace()
}
func (e *xerr) formatSummary() string {
return e.Error()
}
func (e *xerr) formatStacktrace() string {
if e.stacktrace == nil {
return ""
}
rows := make([]string, 0)
recursive(e, func(err *xerr) {
var row string
newline := func() {
if row != "" && !strings.HasSuffix(row, "\n") {
row += "\n"
}
}
if err == nil {
return
}
if err.msg != "" {
row += " Thrown: " + err.msg
}
if err.stacktrace != nil {
if st := err.stacktrace.String(); st != "" {
newline()
row += err.stacktrace.String()
}
}
if strings.TrimSpace(row) != "" {
rows = append(rows, row)
}
})
slices.Reverse(rows)
first := e.Error()
if errcode.IsNotDefaultCode(e.code) {
first = e.code.String() + ": " + first
}
rows = slices.Insert(rows, 0, first)
return strings.Join(rows, "\n")
}
func recursive(e *xerr, tap func(*xerr)) {
tap(e)
if e.err == nil {
return
}
var err *xerr
if ok := errors.As(e.err, &err); ok {
recursive(err, tap)
}
}