-
Notifications
You must be signed in to change notification settings - Fork 5
/
errors.go
390 lines (342 loc) · 10.3 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
// Package errors helps in wrapping errors with custom type as well as a user friendly message. This is particularly useful when responding to APIs
package errors
import (
"fmt"
"io"
"net/http"
"runtime"
"strconv"
"strings"
)
type errType int
func (e errType) Int() int {
return int(e)
}
// While adding a new Type, the respective helper functions should be added, also update the
// WriteHTTP method accordingly
const (
// TypeInternal is error type for when there is an internal system error. e.g. Database errors
TypeInternal errType = iota
// TypeValidation is error type for when there is a validation error. e.g. invalid email address
TypeValidation
// TypeInputBody is error type for when an input data type error. e.g. invalid JSON
TypeInputBody
// TypeDuplicate is error type for when there's duplicate content
TypeDuplicate
// TypeUnauthenticated is error type when trying to access an authenticated API without authentication
TypeUnauthenticated
// TypeUnauthorized is error type for when there's an unauthorized access attempt
TypeUnauthorized
// TypeEmpty is error type for when an expected non-empty resource, is empty
TypeEmpty
// TypeNotFound is error type for an expected resource is not found e.g. user ID not found
TypeNotFound
// TypeMaximumAttempts is error type for attempting the same action more than allowed
TypeMaximumAttempts
// TypeSubscriptionExpired is error type for when a user's 'paid' account has expired
TypeSubscriptionExpired
// TypeDownstreamDependencyTimedout is error type for when a request to a downstream dependent service times out
TypeDownstreamDependencyTimedout
// DefaultMessage is the default user friendly message
DefaultMessage = "unknown error occurred"
)
var (
defaultErrType = TypeInternal
)
// Error is the struct which holds custom attributes
type Error struct {
// original is the original error
original error
// Message is meant to be returned as response of API, so this should be a user-friendly message
message string
// Type is used to define the type of the error, e.g. Server error, validation error etc.
eType errType
fileLine string
pcs []uintptr
}
// Error is the implementation of error interface
func (e *Error) Error() string {
if e.original != nil {
// string concatenation with + is ~100x faster than fmt.Sprintf()
return e.fileLine + ": " + e.message + "\n" + e.original.Error()
}
if e.message != "" {
// string concatenation with + is ~100x faster than fmt.Sprintf()
return e.fileLine + ": " + e.message
}
// string concatenation with + is ~100x faster than fmt.Sprintf()
return e.fileLine + ": " + DefaultMessage
}
// ErrorWithoutFileLine prints the final string without the stack trace / file+line number
func (e *Error) ErrorWithoutFileLine() string {
if e.original != nil {
if e.message != "" {
// string concatenation with + is ~100x faster than fmt.Sprintf()
msg := e.message + ": "
if o, ok := e.original.(*Error); ok {
msg += o.ErrorWithoutFileLine()
} else {
msg += e.original.Error()
}
return msg
}
return e.original.Error()
}
if e.message != "" {
return e.message
}
return e.fileLine
}
// Message returns the user friendly message stored in the error struct. It will ignore all errors
// which are not of type *Error
func (e *Error) Message() string {
messages := make([]string, 0, 5)
if e.message != "" {
messages = append(messages, e.message)
}
err, _ := e.original.(*Error)
for err != nil {
if err.message == "" {
err, _ = err.original.(*Error)
continue
}
messages = append(messages, err.message)
err, _ = err.original.(*Error)
}
if len(messages) > 0 {
return strings.Join(messages, ": ")
}
return e.Error()
}
// Unwrap implement's Go 1.13's Unwrap interface exposing the wrapped error
func (e *Error) Unwrap() error {
return e.original
}
// Is implements the Is interface required by Go
func (e *Error) Is(err error) bool {
o, _ := err.(*Error)
return o == e
}
// HTTPStatusCode is a convenience method used to get the appropriate HTTP response status code for the respective error type
func (e *Error) HTTPStatusCode() int {
status := http.StatusInternalServerError
switch e.eType {
case TypeValidation:
{
status = http.StatusUnprocessableEntity
}
case TypeInputBody:
{
status = http.StatusBadRequest
}
case TypeDuplicate:
{
status = http.StatusConflict
}
case TypeUnauthenticated:
{
status = http.StatusUnauthorized
}
case TypeUnauthorized:
{
status = http.StatusForbidden
}
case TypeEmpty:
{
status = http.StatusGone
}
case TypeNotFound:
{
status = http.StatusNotFound
}
case TypeMaximumAttempts:
{
status = http.StatusTooManyRequests
}
case TypeSubscriptionExpired:
{
status = http.StatusPaymentRequired
}
}
return status
}
// Type returns the error type as integer
func (e *Error) Type() errType {
return e.eType
}
// Format implements the verbs/directives supported by Error to be used in fmt annotated/formatted strings
/*
%v - the same output as Message(). i.e. recursively get all the custom messages set by user
- if any of the wrapped error is not of type *Error, that will *not* be displayed
%+v - recursively prints all the messages along with the file & line number. Also includes output of `Error()` of
non *Error types.
%s - identical to %v
%+s - recursively prints all the messages without file & line number. Also includes output `Error()` of
non *Error types.
*/
func (e *Error) Format(s fmt.State, verb rune) {
switch verb {
case 'v':
if s.Flag('+') {
_, _ = io.WriteString(s, e.Error())
} else {
_, _ = io.WriteString(s, e.Message())
}
case 's':
{
if s.Flag('+') {
_, _ = io.WriteString(s, e.ErrorWithoutFileLine())
} else {
_, _ = io.WriteString(s, e.Message())
}
}
}
}
func (e *Error) RuntimeFrames() *runtime.Frames {
return runtime.CallersFrames(e.pcs)
}
func (e *Error) ProgramCounters() []uintptr {
return e.pcs
}
func (e *Error) StackTrace() string {
trace := make([]string, 0, 100)
rframes := e.RuntimeFrames()
frame, ok := rframes.Next()
line := strconv.Itoa(frame.Line)
trace = append(trace, frame.Function+"(): "+e.message)
for ok {
trace = append(trace, "\t"+frame.File+":"+line)
frame, ok = rframes.Next()
}
return strings.Join(trace, "\n")
}
func (e *Error) StackTraceNoFormat() []string {
trace := make([]string, 0, 100)
rframes := e.RuntimeFrames()
frame, ok := rframes.Next()
line := strconv.Itoa(frame.Line)
trace = append(trace, frame.Function+"(): "+e.message)
for ok {
trace = append(trace, frame.File+":"+line)
frame, ok = rframes.Next()
}
return trace
}
// StackTraceCustomFormat lets you prepare a stacktrace in a custom format
/*
Supported directives:
%m - message
%p - file path
%l - line
%f - function
*/
func (e *Error) StackTraceCustomFormat(msgformat string, traceFormat string) string {
rframes := e.RuntimeFrames()
frame, ok := rframes.Next()
message := strings.ReplaceAll(msgformat, "%m", e.message)
message = strings.ReplaceAll(message, "%p", frame.File)
message = strings.ReplaceAll(message, "%l", strconv.Itoa(frame.Line))
message = strings.ReplaceAll(message, "%f", frame.Function)
traces := make([]string, 0, 100)
traces = append(traces, message)
for ok {
trace := strings.ReplaceAll(traceFormat, "%m", e.message)
trace = strings.ReplaceAll(trace, "%p", frame.File)
trace = strings.ReplaceAll(trace, "%l", strconv.Itoa(frame.Line))
trace = strings.ReplaceAll(trace, "%f", frame.Function)
traces = append(traces, trace)
frame, ok = rframes.Next()
}
return strings.Join(traces, "")
}
// New returns a new instance of Error with the relavant fields initialized
func New(msg string) *Error {
return newerr(nil, msg, defaultErrType)
}
func Newf(fromat string, args ...interface{}) *Error {
return newerrf(nil, defaultErrType, fromat, args...)
}
// Errorf is a convenience method to create a new instance of Error with formatted message
// Important: %w directive is not supported, use fmt.Errorf if you're using the %w directive or
// use Wrap/Wrapf to wrap an error.
func Errorf(fromat string, args ...interface{}) *Error {
return Newf(fromat, args...)
}
// SetDefaultType will set the default error type, which is used in the 'New' function
func SetDefaultType(e errType) {
defaultErrType = e
}
// Stacktrace returns a string representation of the stacktrace, where each trace is separated by a newline and tab '\t'
func Stacktrace(err error) string {
trace := make([]string, 0, 100)
for err != nil {
e, ok := err.(*Error)
if ok {
trace = append(trace, e.StackTrace())
} else {
trace = append(trace, err.Error())
}
err = Unwrap(err)
}
return strings.Join(trace, "\n")
}
// Stacktrace returns a string representation of the stacktrace, as a slice of string where each
// element represents the error message and traces.
func StacktraceNoFormat(err error) []string {
trace := make([]string, 0, 100)
for err != nil {
e, ok := err.(*Error)
if ok {
trace = append(trace, e.StackTraceNoFormat()...)
} else {
trace = append(trace, err.Error())
}
err = Unwrap(err)
}
return trace
}
// StacktraceCustomFormat lets you prepare a stacktrace in a custom format
/*
msgformat - is used to format the line which prints message from Error.message
traceFormat - is used to format the line which prints trace
Supported directives:
%m - message if err type is *Error, otherwise output of `.Error()`
%p - file path, empty if type is not *Error
%l - line, empty if type is not *Error
%f - function, empty if type is not *Error
*/
func StacktraceCustomFormat(msgformat string, traceFormat string, err error) string {
trace := make([]string, 0, 100)
for err != nil {
e, ok := err.(*Error)
if ok {
trace = append(trace, e.StackTraceCustomFormat(msgformat, traceFormat))
} else {
message := strings.ReplaceAll(msgformat, "%m", err.Error())
message = strings.ReplaceAll(message, "%p", "")
message = strings.ReplaceAll(message, "%l", "")
message = strings.ReplaceAll(message, "%f", "")
trace = append(
trace,
message,
)
}
err = Unwrap(err)
}
return strings.Join(trace, "")
}
func ProgramCounters(err error) []uintptr {
pcs := make([]uintptr, 0, 100)
for err != nil {
e, ok := err.(*Error)
if ok {
pcs = append(pcs, e.ProgramCounters()...)
}
err = Unwrap(err)
}
return pcs
}
func RuntimeFrames(err error) *runtime.Frames {
pcs := ProgramCounters(err)
return runtime.CallersFrames(pcs)
}