-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcustomerror.go
More file actions
739 lines (564 loc) · 16.6 KB
/
customerror.go
File metadata and controls
739 lines (564 loc) · 16.6 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
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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
// Copyright 2021 The customerror Authors. All rights reserved.
// Use of this source code is governed by a MIT
// license that can be found in the LICENSE file.
package customerror
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strings"
"sync"
"github.com/emirpasic/gods/sets/treeset"
"github.com/go-playground/validator/v10"
)
//////
// Helpers.
//////
// Copy performs a deep copy of the src CustomError into the target CustomError.
// It ensures that all fields, including nested structures like maps and sets,
// are properly copied. This function is useful when you need to create a new
// CustomError instance based on an existing one, while avoiding any shared
// references to mutable fields.
func Copy(src, target *CustomError) *CustomError {
if src.Code != "" {
target.Code = src.Code
}
if src.Retryable {
target.Retryable = src.Retryable
}
if src.Retried {
target.Retried = src.Retried
}
if src.Err != nil {
target.Err = src.Err
}
if src.language != "" {
target.language = src.language
}
if src.Message != "" {
target.Message = src.Message
}
if src.StatusCode != 0 {
target.StatusCode = src.StatusCode
}
if src.ignore {
target.ignore = src.ignore
}
// Merge the language messages.
if src.LanguageMessageMap != nil {
if target.LanguageMessageMap == nil {
target.LanguageMessageMap = &sync.Map{}
}
finalLanguageMessageMap := &sync.Map{}
src.LanguageMessageMap.Range(func(key, value interface{}) bool {
finalLanguageMessageMap.Store(key, value)
return true
})
target.LanguageMessageMap.Range(func(key, value interface{}) bool {
finalLanguageMessageMap.Store(key, value)
return true
})
target.LanguageMessageMap = finalLanguageMessageMap
}
// Merge fields.
if src.Fields != nil {
if target.Fields == nil {
target.Fields = &sync.Map{}
}
finalFields := &sync.Map{}
src.Fields.Range(func(key, value interface{}) bool {
finalFields.Store(key, value)
return true
})
target.Fields.Range(func(key, value interface{}) bool {
finalFields.Store(key, value)
return true
})
target.Fields = finalFields
}
// Merge the tags.
if src.Tags != nil {
if target.Tags == nil {
target.Tags = &Set{treeset.NewWithStringComparator()}
}
src.Tags.Each(func(_ int, value interface{}) {
target.Tags.Add(value)
})
}
return target
}
// Process fields and add them to the error message.
func processFields(
errMsg string,
fields *sync.Map,
) string {
if fields != nil {
errMsg = fmt.Sprintf("%s. Fields:", errMsg)
fields.Range(func(k, v interface{}) bool {
errMsg = fmt.Sprintf("%s %s=%v,", errMsg, k, v)
return true
})
errMsg = strings.TrimSuffix(errMsg, ",")
}
return errMsg
}
// mapToSyncMap converts a map to a sync.Map.
func mapToSyncMap(m map[string]interface{}) *sync.Map {
sm := &sync.Map{}
for k, v := range m {
sm.Store(k, v)
}
return sm
}
// syncMapToMap converts a sync.Map to a map.
func syncMapToMap(sm *sync.Map) map[string]interface{} {
m := make(map[string]interface{})
if sm != nil {
sm.Range(func(k, v interface{}) bool {
if str, ok := k.(string); ok {
m[str] = v
}
return true
})
}
return m
}
// Set is a wrapper around the treeset.Set, providing a collection
// that stores unique elements in a sorted order. It is used in the
// CustomError struct to maintain a sorted set of tags.
type Set struct {
*treeset.Set
}
// String implements the Stringer interface for the Set type.
// It returns a comma-separated string representation of all elements
// in the set, useful for debugging and error message formatting.
func (s *Set) String() string {
items := []string{}
s.Each(func(_ int, value interface{}) {
items = append(items, fmt.Sprintf("%v", value))
})
return strings.Join(items, ", ")
}
// CustomError is the base block to create custom errors. It provides context -
// a `Message` to an optional `Err`. Additionally a `Code` - for example "E1010",
// and `StatusCode` can be provided.
type CustomError struct {
// Code can be any custom code, e.g.: E1010.
Code string `json:"code,omitempty" validate:"omitempty,gte=2"`
// Err optionally wraps the original error.
Err error `json:"-"`
// Field enhances the error message with more structured information.
Fields *sync.Map `json:"fields,omitempty"`
// Human readable message. Minimum length: 3.
Message string `json:"message" validate:"required,gte=3"`
// Message in different languages.
LanguageMessageMap LanguageMessageMap `json:"languageMessageMap"`
// LanguageErrorTypeMap is a map of language prefixes to templates such
// as "missing %s", "%s required", "%s invalid", etc.
LanguageErrorTypeMap LanguageErrorMap `json:"languageErrorTypeMap"`
// Retryable indicates if the error is retryable.
Retryable bool `json:"retryable"`
// Retried indicates if the error has been retried.
Retried bool `json:"retried"`
// StatusCode is a valid HTTP status code, e.g.: 404.
StatusCode int `json:"-" validate:"omitempty,gte=100,lte=511"`
// Tags is a SET of tags which helps to categorize the error.
Tags *Set `json:"tags,omitempty"`
// If set to true, the error will be ignored (return nil).
ignore bool `json:"-"`
// Language to be use for the message and prefix.
language Language
}
//////
// Error interface implementation.
//////
// Error interface implementation returns the properly formatted error message.
// It will contain `Code`, `Tags`, `Fields` and any wrapped error.
func (cE *CustomError) Error() string {
errMsg := cE.Message
if cE.Code != "" {
if cE.Message != cE.Code {
errMsg = fmt.Sprintf("%s: %s", cE.Code, errMsg)
} else {
errMsg = cE.Code
}
}
if cE.Err != nil {
errMsg = fmt.Errorf("%s. Original Error: %w", errMsg, cE.Err).Error()
}
if cE.Tags != nil {
errMsg = fmt.Sprintf("%s. Tags: %s", errMsg, cE.Tags.String())
}
errMsg = processFields(errMsg, cE.Fields)
if cE.Retryable {
errMsg = fmt.Sprintf("%s. Retryable: %t. Retried: %t", errMsg, cE.Retryable, cE.Retried)
}
return errMsg
}
// Is interface implementation ensures chain continuity. Treats `CustomError` as
// equivalent to `err`.
//
// SEE https://blog.golang.org/go1.13-errors
//
//nolint:errorlint
func (cE *CustomError) Is(err error) bool {
return cE.Err == err
}
// Unwrap interface implementation returns inner error.
func (cE *CustomError) Unwrap() error {
return cE.Err
}
//////
// Implementing the json.Marshaler interface.
//////
// MarshalJSON implements the json.Marshaler interface.
//
// SEE https://gist.github.com/thalesfsp/3a1252530750e2370345a2418721ff54
func (cE *CustomError) MarshalJSON() ([]byte, error) {
// Define a temporary map that matches the desired JSON format.
temp := make(map[string]interface{})
// Populate the temporary map.
temp["message"] = cE.JustError()
if cE.Code != "" {
temp["code"] = cE.Code
}
if cE.Tags != nil && !cE.Tags.Empty() {
temp["tags"] = cE.Tags
}
if cE.Retryable {
temp["retryable"] = cE.Retryable
}
if cE.Retried {
temp["retried"] = cE.Retried
}
if cE.Fields != nil {
// Convert the sync.Map to a regular map so that we can iterate over its keys.
fields := syncMapToMap(cE.Fields)
// Populate the fields of the temporary map.
if len(fields) > 0 {
for k, v := range fields {
if k != "" && v != nil {
temp[k] = v
}
}
}
}
if cE.StatusCode > 0 {
temp["statusCode"] = cE.StatusCode
}
// Serialize the temporary map to JSON.
return json.Marshal(temp)
}
//////
// Error message formatting.
//////
// JustError returns the error message without any additional information.
func (cE *CustomError) JustError() string {
errMsg := cE.Message
if cE.Err != nil {
errMsg = fmt.Errorf("%s. Original Error: %w", errMsg, cE.Err).Error()
}
return errMsg
}
// APIError is like error plus status code information.
func (cE *CustomError) APIError() string {
errMsg := cE.Message
if cE.Code != "" {
if cE.Message != cE.Code {
errMsg = fmt.Sprintf("%s: %s", cE.Code, errMsg)
} else {
errMsg = cE.Code
}
}
if cE.StatusCode != 0 {
if cE.Message != http.StatusText(cE.StatusCode) {
errMsg = fmt.Sprintf("%s (%d - %s)", errMsg, cE.StatusCode, http.StatusText(cE.StatusCode))
} else {
errMsg = fmt.Sprintf("%s (%d)", errMsg, cE.StatusCode)
}
}
if cE.Err != nil {
errMsg = fmt.Errorf("%s. Original Error: %w", errMsg, cE.Err).Error()
}
if cE.Tags != nil {
errMsg = fmt.Sprintf("%s. Tags: %s", errMsg, cE.Tags.String())
}
errMsg = processFields(errMsg, cE.Fields)
if cE.Retryable {
errMsg = fmt.Sprintf("%s. Retryable: %t. Retried: %t", errMsg, cE.Retryable, cE.Retried)
}
return errMsg
}
// FormatError formats the error message with the given error type.
func (cE *CustomError) FormatError(errorType string, opts ...Option) *CustomError {
if cE == nil {
return nil
}
finalCE := &CustomError{}
finalCE = Copy(cE, finalCE)
// Apply options.
for _, opt := range opts {
opt(finalCE)
}
if finalCE.language != "" {
// Get the template by the language.
template, err := GetTemplate(string(finalCE.language), errorType)
if err != nil {
// Get the template by the root language.
template2, err := GetTemplate(finalCE.language.GetRoot(), errorType)
if err != nil {
panic(err)
}
template = template2
}
finalCE.Message = fmt.Sprintf(template, finalCE.Message)
return finalCE
}
return finalCE
}
//////
// Factory methods.
//////
// NewFailedToError is the building block for errors usually thrown when some
// action failed, e.g: "Failed to create host". Default status code is `500`.
//
// NOTE: Preferably don't use with the `WithLanguage` because of the "Failed to"
// part. Prefer to use `New` instead.
//
// NOTE: Status code can be redefined, call `SetStatusCode`.
func (cE *CustomError) NewFailedToError(opts ...Option) error {
finalCE := cE.FormatError(string(FailedTo), opts...)
if finalCE.language == "" {
finalCE = Copy(NewFailedToError(finalCE.Message, opts...).(*CustomError), finalCE)
return finalCE
}
return finalCE
}
// NewInvalidError is the building block for errors usually thrown when
// something fail validation, e.g: "Invalid port". Default status code is `400`.
//
// NOTE: Preferably don't use with the `WithLanguage` because of the "Invalid"
// part. Prefer to use `New` instead.
//
// NOTE: Status code can be redefined, call `SetStatusCode`.
func (cE *CustomError) NewInvalidError(opts ...Option) error {
finalCE := cE.FormatError(string(Invalid), opts...)
if finalCE.language == "" {
finalCE = Copy(NewInvalidError(finalCE.Message, opts...).(*CustomError), finalCE)
return finalCE
}
return finalCE
}
// NewMissingError is the building block for errors usually thrown when required
// information is missing, e.g: "Missing host". Default status code is `400`.
//
// NOTE: Preferably don't use with the `WithLanguage` because of the "Missing"
// part. Prefer to use `New` instead.
//
// NOTE: Status code can be redefined, call `SetStatusCode`.
func (cE *CustomError) NewMissingError(opts ...Option) error {
finalCE := cE.FormatError(Missing.String(), opts...)
if finalCE.language == "" {
finalCE = Copy(NewMissingError(finalCE.Message, opts...).(*CustomError), finalCE)
return finalCE
}
return finalCE
}
// NewRequiredError is the building block for errors usually thrown when
// required information is missing, e.g: "Port is required". Default status code is `400`.
//
// NOTE: Preferably don't use with the `WithLanguage` because of the "Required"
// part. Prefer to use `New` instead.
//
// NOTE: Status code can be redefined, call `SetStatusCode`.
func (cE *CustomError) NewRequiredError(opts ...Option) error {
finalCE := cE.FormatError(Required.String(), opts...)
if finalCE.language == "" {
finalCE = Copy(NewRequiredError(finalCE.Message, opts...).(*CustomError), finalCE)
return finalCE
}
return finalCE
}
// NewHTTPError is the building block for simple HTTP errors, e.g.: Not Found.
//
// NOTE: `WithLanguage` has no effect on it because of it's just a simple HTTP
// error.
//
// NOTE: Status code can be redefined, call `SetStatusCode`.
func (cE *CustomError) NewHTTPError(statusCode int, opts ...Option) error {
if cE == nil {
return nil
}
if cE.StatusCode == 0 {
cE.StatusCode = statusCode
}
finalCE := &CustomError{}
finalCE = Copy(cE, finalCE)
httpCE := NewHTTPError(finalCE.StatusCode, opts...).(*CustomError)
finalErrorMessage := httpCE.Message
// Apply options.
for _, opt := range opts {
opt(finalCE)
}
finalCE.Message = finalErrorMessage
finalCE = Copy(httpCE, finalCE)
return finalCE
}
// New is the building block for other errors. Preferred method to be used for
// translations (WithLanguage).
func (cE *CustomError) New(opts ...Option) error {
if cE == nil {
return nil
}
finalCE := &CustomError{}
finalCE = Copy(cE, finalCE)
// Apply options.
for _, opt := range opts {
opt(finalCE)
}
finalCE = Copy(New(finalCE.Message, opts...).(*CustomError), finalCE)
return finalCE
}
//////
// Exported functionalities.
//////
// Wrap `customError` around `errors`.
func Wrap(customError error, errors ...error) error {
errMsgs := []string{}
for _, err := range errors {
if err != nil {
errMsgs = append(errMsgs, err.Error())
}
}
return fmt.Errorf("%w. Wrapped Error(s): %s", customError, strings.Join(errMsgs, ". "))
}
// NewChildError creates a new `CustomError` with the same fields and tags of
// the parent `CustomError` plus the new fields and tags passed as arguments.
func (cE *CustomError) NewChildError(opts ...Option) *CustomError {
childCE := &CustomError{}
// Apply the options.
for _, opt := range opts {
opt(childCE)
}
return Copy(cE, childCE)
}
// SetMessage sets the message of the error.
func (cE *CustomError) SetMessage(message string) {
cE.Message = message
}
// SetRetried sets if the error has been retried.
func (cE *CustomError) SetRetried(status bool) {
cE.Retried = status
}
//////
// Factory.
//////
// Base newInternal.
func newInternal(opts ...Option) *CustomError {
cE := &CustomError{}
// Apply options.
for _, opt := range opts {
opt(cE)
}
// Should use status code if no message is set. Status code should be
// priority.
if cE.Message == "" && cE.StatusCode > 0 {
cE.Message = http.StatusText(cE.StatusCode)
} else if cE.Message == "" && cE.Code != "" {
cE.Message = cE.Code
}
return cE
}
// New creates a new validated custom error returning it as en `error`.
//
//nolint:revive
func New(message string, opts ...Option) error {
cE := newInternal(prependOptions(opts, WithMessage(message))...)
// Should be able to programatically ignore errors (`WithIgnoreFunc`).
if cE.ignore {
return nil
}
if cE == nil {
log.Panicln("Failed to create custom error.")
}
if err := validator.New().Struct(cE); err != nil {
if os.Getenv("CUSTOMERROR_ENVIRONMENT") == "testing" {
log.Panicf("Invalid custom error. %s\n", err)
}
log.Fatalf("Invalid custom error. %s\n", err)
return nil
}
return cE
}
// Factory creates a validated and pre-defined error to be recalled and thrown
// later, with or without options. Possible options are:
// - `NewFailedToError`
// - `NewInvalidError`
// - `NewMissingError`
// - `NewRequiredError`
// - `NewHTTPError`.
func Factory(message string, opts ...Option) *CustomError {
cE := newInternal(prependOptions(opts, WithMessage(message))...)
// Should be able to programatically ignore errors (`WithIgnoreFunc`).
if cE.ignore {
return nil
}
if cE == nil {
log.Panicln("Failed to create custom error.")
}
return cE
}
// IsCustomError checks if the error is a `CustomError`.
func IsCustomError(err error) bool {
_, ok := err.(*CustomError)
return ok
}
// To converts the error to a `CustomError`.
func To(err error) (*CustomError, bool) {
cE, ok := err.(*CustomError)
if !ok {
return nil, false
}
return cE, true
}
// From modifies the error with the given options, if `err` isn't a custom error
// it then returns a new custom error with the given options.
func From(err error, opts ...Option) error {
if cE, ok := To(err); ok {
for _, opt := range opts {
opt(cE)
}
return cE
}
// WithError properly deals with Golang errors (unwrapping, etc).
opts = append(opts, WithError(err))
return New(err.Error(), opts...)
}
// IsHTTPStatus checks if the error is a `CustomError` with the
// specified HTTP status code.
func IsHTTPStatus(err error, statusCode int) bool {
cE, ok := err.(*CustomError)
if !ok {
return false
}
return cE.StatusCode == statusCode
}
// IsErrorCode checks if the error is a `CustomError` with the
// specified code.
func IsErrorCode(err error, code string) bool {
cE, ok := err.(*CustomError)
if !ok {
return false
}
return cE.Code == code
}
// IsRetryable checks if the error is a retryable `CustomError`.
func IsRetryable(err error) bool {
cE, ok := err.(*CustomError)
if !ok {
return false
}
return cE.Retryable
}