-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrors.go
More file actions
266 lines (224 loc) · 7.15 KB
/
errors.go
File metadata and controls
266 lines (224 loc) · 7.15 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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
package errors
import (
stderrors "errors"
"fmt"
"runtime"
"strings"
"google.golang.org/grpc/codes"
grpcstatus "google.golang.org/grpc/status"
)
// SupportPackageIsVersion1 is a compile-time assertion constant.
// Downstream packages reference this to enforce version compatibility.
const SupportPackageIsVersion1 = true
var (
basePath = ""
maxStackDepth = 64
)
// StackFrame represents the stackframe for tracing exception
type StackFrame struct {
File string `json:"file"`
Line int `json:"line"`
Func string `json:"function"`
}
// ErrorExt is the interface that defines a error, any ErrorExt implementors can use and override errors and notifier package
type ErrorExt interface {
// embeds the error interface
error
// Callers returns the call poiners for the stack
Callers() []uintptr
// StackFrame returns the stack frame for the error
StackFrame() []StackFrame
//Cause returns the original error object that caused this error
Cause() error
//GRPCStatus allows ErrorExt to be treated as a GRPC Error
GRPCStatus() *grpcstatus.Status
}
// NotifyExt is the interface definition for notifier related options
type NotifyExt interface {
// ShouldNotify returns true if the error should be notified
ShouldNotify() bool
// Notified sets the error to be notified or not
Notified(status bool)
}
type customError struct {
Msg string
stack []uintptr
frame []StackFrame
cause error
wrapped error // immediate parent for Unwrap() chain; may differ from cause
shouldNotify bool
status *grpcstatus.Status
}
// ShouldNotify returns true if the error should be reported to notifiers.
func (c *customError) ShouldNotify() bool {
return c.shouldNotify
}
// Notified marks the error as having been notified (or not).
func (c *customError) Notified(status bool) {
c.shouldNotify = !status
}
// Error returns the error message.
func (c customError) Error() string {
return c.Msg
}
// Callers returns the program counters of the call stack when the error was created.
func (c customError) Callers() []uintptr {
return c.stack[:]
}
// StackTrace returns the program counters of the call stack (alias for Callers).
func (c customError) StackTrace() []uintptr {
return c.Callers()
}
// StackFrame returns the structured stack frames for the error.
func (c customError) StackFrame() []StackFrame {
return c.frame
}
// Cause returns the root cause error that originated this error chain.
func (c customError) Cause() error {
return c.cause
}
// GRPCStatus returns the gRPC status for this error.
func (c customError) GRPCStatus() *grpcstatus.Status {
if c.status != nil {
// use latest error message and keep other data (e.g. details)
newStatus := c.status.Proto()
newStatus.Message = c.Error()
return grpcstatus.FromProto(newStatus)
}
return grpcstatus.New(codes.Internal, c.Error())
}
func (c *customError) generateStack(skip int) []StackFrame {
stack := []StackFrame{}
trace := []uintptr{}
for i := skip + 1; i < skip+1+maxStackDepth; i++ {
pc, file, line, ok := runtime.Caller(i)
if !ok {
break
}
_, funcName := packageFuncName(pc)
if basePath != "" {
file = strings.Replace(file, basePath, "", 1)
}
stack = append(stack, StackFrame{
File: file,
Line: line,
Func: funcName,
})
trace = append(trace, pc)
}
c.frame = stack
c.stack = trace
return stack
}
// Unwrap returns the immediate parent error for use with errors.Is and errors.As.
func (c customError) Unwrap() error {
return c.wrapped
}
func packageFuncName(pc uintptr) (string, string) {
f := runtime.FuncForPC(pc)
if f == nil {
return "", ""
}
packageName := ""
funcName := f.Name()
if ind := strings.LastIndex(funcName, "/"); ind > 0 {
packageName += funcName[:ind+1]
funcName = funcName[ind+1:]
}
if ind := strings.Index(funcName, "."); ind > 0 {
packageName += funcName[:ind]
funcName = funcName[ind+1:]
}
return packageName, funcName
}
// New creates a new error with stack information
func New(msg string) ErrorExt {
return NewWithSkip(msg, 1)
}
// NewWithStatus creates a new error with statck information and GRPC status
func NewWithStatus(msg string, status *grpcstatus.Status) ErrorExt {
return NewWithSkipAndStatus(msg, 1, status)
}
// NewWithSkip creates a new error skipping the number of function on the stack
func NewWithSkip(msg string, skip int) ErrorExt {
return WrapWithSkip(stderrors.New(msg), "", skip+1)
}
// NewWithSkipAndStatus creates a new error skipping the number of function on the stack and GRPC status
func NewWithSkipAndStatus(msg string, skip int, status *grpcstatus.Status) ErrorExt {
return WrapWithSkipAndStatus(stderrors.New(msg), "", skip+1, status)
}
// Wrap wraps an existing error and appends stack information if it does not exists
func Wrap(err error, msg string) ErrorExt {
return WrapWithSkip(err, msg, 1)
}
// Wrap wraps an existing error and appends stack information if it does not exists along with GRPC status
func WrapWithStatus(err error, msg string, status *grpcstatus.Status) ErrorExt {
return WrapWithSkipAndStatus(err, msg, 1, status)
}
// WrapWithSkip wraps an existing error and appends stack information if it does not exists skipping the number of function on the stack
func WrapWithSkip(err error, msg string, skip int) ErrorExt {
return WrapWithSkipAndStatus(err, msg, skip+1, nil)
}
// WrapWithSkip wraps an existing error and appends stack information if it does not exists skipping the number of function on the stack along with GRPC status
func WrapWithSkipAndStatus(err error, msg string, skip int, status *grpcstatus.Status) ErrorExt {
if err == nil {
return nil
}
msg = strings.TrimSpace(msg)
if msg != "" {
msg = msg + ": "
}
if status == nil {
// try to get status from existing one from error
if s, ok := grpcstatus.FromError(err); ok {
status = s
}
}
//if we have stack information reuse that
if e, ok := err.(ErrorExt); ok {
c := &customError{
Msg: msg + e.Error(),
cause: e.Cause(),
wrapped: err, // preserve full chain for errors.Is/errors.As
status: status,
shouldNotify: true,
}
c.stack = e.Callers()
c.frame = e.StackFrame()
if n, ok := e.(NotifyExt); ok {
c.shouldNotify = n.ShouldNotify()
}
return c
}
c := &customError{
Msg: msg + err.Error(),
cause: err,
wrapped: err,
shouldNotify: true,
status: status,
}
c.generateStack(skip + 1)
return c
}
// SetMaxStackDepth sets the maximum number of stack frames captured when creating errors.
// Default is 64. Must be called during initialization.
func SetMaxStackDepth(n int) {
if n > 0 {
maxStackDepth = n
}
}
// Newf creates a new error with a formatted message and stack information
func Newf(format string, args ...any) ErrorExt {
return NewWithSkip(fmt.Sprintf(format, args...), 1)
}
// Wrapf wraps an existing error with a formatted message and appends stack information if it does not exist
func Wrapf(err error, format string, args ...any) ErrorExt {
return WrapWithSkip(err, fmt.Sprintf(format, args...), 1)
}
// SetBaseFilePath sets the base file path for linking source code with reported stack information
func SetBaseFilePath(path string) {
path = strings.TrimSpace(path)
if path != "" {
basePath = path
}
}