/
errors.go
402 lines (336 loc) · 9.62 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
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
package e
import (
"context"
"fmt"
"net/http"
"runtime"
"strconv"
"strings"
"github.com/davecgh/go-spew/spew"
"github.com/getsentry/sentry-go"
"github.com/golang/protobuf/proto"
"google.golang.org/genproto/googleapis/rpc/errdetails"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
var (
// verify that Err conforms to the GRPC status interface
_ interface {
GRPCStatus() *status.Status
} = (*Err)(nil)
)
// Err defines an error with an optional stacktrace and contextual data
type Err struct {
rootErr error
// raw data captured at the moment the error was initially wrapped
rawStack []byte
memStats *runtime.MemStats
// frames that weren't skipped/truncated from the rawStack parse
frames stackframes
// if findFrame fails, frame data is stored here. This typically
// only happens when wrapping across goroutine boundaries, as that
// leaves the
unknownFrames stackframes
currentFrameIdx int
topAppFrame *frame
// contextual data set from WrapOptions
Level Level
code codes.Code
tags map[string]string
isRetriable bool
noReport bool
isPanic bool
isInfra bool
skipFrames int
// contextual data set from ReportOptions
fromHandler bool
shouldWait bool
sentryClient *sentry.Client
}
type stackframes []*frame
type frame struct {
msg string
file string
path string
pkg string
fn string
full string
line int
class class
vars map[string]interface{}
// errDetails contains proto messages containing detailed descriptions
// ex. errdetails.FieldViolations, errdetails.Help, errdetails.PreconditionFailure.
errDetails []proto.Message
}
type class int
const (
// this frame is application logic
classApp = 1
// this frame is our internal pkg
classPkg = 2
// this frame is vendored code
classVendor = 3
// this frame is from the stdlib
classStdLib = 4
// this frame is a panic
classPanic = 5
)
// Level represents an error severity level
type Level int
const (
// LevelCritical = 1
LevelCritical Level = 1
// LevelError = 1
LevelError Level = 2
// LevelWarning = 1
LevelWarning Level = 3
)
// String fulfills the Stringer interface
func (err *Err) String() string {
return err.Error()
}
type causer interface {
Cause() error
}
type unwrapper interface {
Unwrap() error
}
// Cause returns the root cause of the error without the extra wrapped data.
// Supports our own errors, Dave Cheney's pkg/errors, and anything that implements
// either the Cause() error or Unwrap() error interface.
func Cause(rawErr error) error {
switch err := rawErr.(type) {
case *Err:
return err.rootErr
case unwrapper:
return Cause(err.Unwrap())
case causer:
return Cause(err.Cause())
default:
return rawErr
}
}
// Unwrap fulfills the stdlib Unwrap interface
func (err *Err) Unwrap() error {
return err.rootErr
}
// Error fulfills the error interface
func (err *Err) Error() string {
buf := getBuffer()
defer putBuffer(buf)
// print out the simple error string for easy consumption
buf.WriteString(err.rootErr.Error())
buf.WriteByte('\n')
buf.WriteByte('\n')
buf.WriteString("Error Code: ")
buf.WriteString(err.code.String())
buf.WriteByte('\n')
// print out a link to where the error occurred
buf.WriteString(err.githubURL())
buf.WriteByte('\n')
buf.WriteByte('\n')
// callout that this task isn't retriable
if !err.isRetriable {
buf.WriteString("--- NOT RETRIABLE ---\n\n")
}
// print out our organized stack trace with any added context
buf.WriteString(err.frames.String())
// extra reporting if unknown frames were found
if len(err.unknownFrames) > 0 {
buf.WriteString("\n\n--- UNKNOWN STACK FRAMES FOUND ---")
buf.WriteString(err.unknownFrames.String())
}
// spew out the full error with type info if it is anything but errors.New()
errStr := fmt.Sprintf("%#v", err.rootErr)
if !strings.HasPrefix(errStr, "&errors.errorString") {
buf.WriteString("\nErr: ")
buf.WriteString(spew.Sdump(err.rootErr))
}
return buf.String()
}
// Location returns the path/file/line where the first New/Wrap happened
func Location(rawErr error) (string, string, int) {
err, ok := rawErr.(*Err)
if !ok || len(err.frames) == 0 {
return "", "", 0
}
f := err.frames[0]
return f.path, f.file, f.line
}
// CodeFromHTTPStatus does the inverse of HTTPStatusFromCode. It's a lossy conversion as there isn't a 1 to 1 mapping
func CodeFromHTTPStatus(statusCode int) codes.Code {
switch statusCode {
case http.StatusOK:
return codes.OK
case http.StatusRequestTimeout:
return codes.Canceled
case http.StatusInternalServerError:
return codes.Unknown
case http.StatusBadRequest:
return codes.InvalidArgument
case http.StatusGatewayTimeout:
return codes.DeadlineExceeded
case http.StatusNotFound:
return codes.NotFound
case http.StatusConflict:
return codes.AlreadyExists
case http.StatusForbidden:
return codes.PermissionDenied
case http.StatusUnauthorized:
return codes.Unauthenticated
case http.StatusTooManyRequests:
return codes.ResourceExhausted
case http.StatusNotImplemented:
return codes.Unimplemented
case http.StatusServiceUnavailable:
return codes.Unavailable
default:
return codes.Unknown
}
}
// Code returns the error code
func (err *Err) Code() codes.Code {
return err.code
}
// CodeFromError returns the error code from an error if there is one.
// Returns OK if err is nil and Unknown if it isn't a wrapped error.
func CodeFromError(err error) codes.Code {
if err == nil {
return codes.OK
}
typedErr, ok := err.(*Err)
if !ok {
return codes.Unknown
}
return typedErr.code
}
// IsRetriable returns whether or not a retry might succeed
func (err *Err) IsRetriable() bool {
return err.isRetriable
}
// githubURL returns a direct link to the line where the first New/Wrap happened
// https://github.com/nozzle/nozzle/blob/ab15cc7c4cf7ed21fcaa8957ef390dbdbc7e1816/namespaces/publish/rankings_client.go#L11
func (err *Err) githubURL() string {
if len(err.frames) == 0 {
return ""
}
buf := getBuffer()
defer putBuffer(buf)
d := err.frames[0]
buf.WriteString("https://github.com/nozzle/e/blob/")
buf.WriteString("main")
buf.WriteString(strings.TrimPrefix(d.path, "github.com/nozzle/e"))
buf.WriteByte('/')
buf.WriteString(d.file)
buf.WriteString("#L")
buf.WriteString(strconv.Itoa(d.line))
return buf.String()
}
func (err *Err) currentFrame() *frame {
// don't panic if the current frame is unknown from the stack parse
if err.currentFrameIdx == -1 {
return err.unknownFrames[len(err.unknownFrames)-1]
}
return err.frames[err.currentFrameIdx]
}
func (fs stackframes) String() string {
buf := getBuffer()
defer putBuffer(buf)
buf.WriteString("-------------------------------\n")
for i := range fs {
buf.WriteString(fs[i].String())
buf.WriteString("\n")
}
return buf.String()
}
const maxLogStringLen = 500
func (f frame) String() string {
buf := getBuffer()
defer putBuffer(buf)
// write the user provided message if there is one
if f.msg != "" {
buf.WriteString("*** ")
buf.WriteString(f.msg)
buf.WriteByte('\n')
}
// write the file, line and function name
// e.g. errors_test.go:103 - TestRecursiveWrap.func1
buf.WriteString(fmt.Sprintf("%s.%s", f.pkg, f.fn))
buf.WriteString(fmt.Sprintf("\n %s/%s:%d", f.path, f.file, f.line))
for k, v := range f.vars {
switch t := v.(type) {
case fmt.Stringer:
str := t.String()
// limit the max length of the string to be logged
if len(str) > maxLogStringLen {
str = str[:maxLogStringLen]
}
buf.WriteString(fmt.Sprintf("\n + %s: %#v", k, str))
case string:
// limit the max length of the string to be logged
if len(t) > maxLogStringLen {
t = t[:maxLogStringLen]
}
buf.WriteString(fmt.Sprintf("\n + %s: %#v", k, t))
case []byte:
// limit the max length of the string to be logged
if len(t) > maxLogStringLen {
t = t[:maxLogStringLen]
}
buf.WriteString(fmt.Sprintf("\n + %s: %#v", k, string(t)))
default:
buf.WriteString(fmt.Sprintf("\n + %s: %#v", k, v))
}
}
// if we have error details include those in the message
for _, detail := range f.errDetails {
buf.WriteByte('\n')
switch t := detail.(type) {
case *errdetails.BadRequest:
buf.WriteString(" + Bad Request:")
for _, violation := range t.FieldViolations {
buf.WriteString(fmt.Sprintf("\n\t%s: %s", violation.Field, violation.Description))
}
default:
buf.WriteString(" + Unknown ErrDetail: ")
buf.WriteString(t.String())
}
}
buf.WriteString("\n-------------------------------")
return buf.String()
}
// NewErrRequiredArg will build a structured error with errdetails
func NewErrRequiredArg(c context.Context, fields ...string) error {
opts := []WrapOption{
Code(codes.InvalidArgument),
}
for _, field := range fields {
opts = append(opts, FieldViolation(field, field+" is required"), With("required field", field))
}
return New("required argument is missing", opts...)
}
// NewErrForbiddenArg creates an error with not allowed fields
func NewErrForbiddenArg(c context.Context, fields ...string) error {
opts := []WrapOption{
Code(codes.InvalidArgument),
}
for _, field := range fields {
opts = append(opts, FieldViolation(field, field+" is not allowed"), With("disallowed field", field))
}
return New("forbidden argument", opts...)
}
// NewErrInvalidArg will return an error with an invalid field and why it was invalid
func NewErrInvalidArg(c context.Context, fields ...string) error {
if len(fields)%2 == 1 {
panic("odd number of arguments passed")
}
opts := []WrapOption{
Code(codes.InvalidArgument),
}
for len(fields) > 0 {
field, description := fields[0], fields[1]
opts = append(opts, FieldViolation(field, description), With(field, description))
fields = fields[2:]
}
return New("invalid argument", opts...)
}