-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcore.go
More file actions
831 lines (695 loc) · 18.9 KB
/
core.go
File metadata and controls
831 lines (695 loc) · 18.9 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
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
package errors
import (
"encoding/json"
"errors"
"fmt"
"reflect"
"regexp"
"strings"
)
const regex = `^(?:\[CODE]: (.+?) )?` + // 1: code (optional)
`\[CAUSE]: \(([^:]+):(\d+)\) ([^:]+): (.+?)` + // 2: file, 3: line, 4: func, 5: msg
`(?: \[METADATA]: (.+?))?` + // 6: metadata (optional)
` \[STACK]:\s*([\s\S]+)` // 7: stack
const snapshotRegex = `^\[CODE]: (.+?) \[MESSAGE]: (.+)$`
const inheritSep = "----------------\n\t\t|\t[INHERITED BY]: "
var (
compiledRegex = regexp.MustCompile(regex)
compiledSnapshotRegex = regexp.MustCompile(snapshotRegex)
)
func Is(err, target error) bool {
if err == nil || target == nil {
return false
}
var mErr, mTarget *Err
errString := err.Error()
if As(err, &mErr) {
if mErr.IsTarget() {
return false
}
errString = mErr.Error()
}
targetString := target.Error()
targetContains := targetString
if As(target, &mTarget) {
targetString = mTarget.Snapshot()
if mTarget.HasCode() {
targetContains = mTarget.Code()
} else {
targetContains = mTarget.Message()
}
}
return errString == targetString || strings.Contains(errString, targetContains)
}
func IsNot(err, target error) bool {
return !Is(err, target)
}
func ContainsCode(err error, code string) bool {
if err == nil || code == "" {
return false
}
pattern := fmt.Sprintf(`\[CODE\]:\s*%s(\s|\])`, regexp.QuoteMeta(code))
re := regexp.MustCompile(pattern)
return re.MatchString(err.Error())
}
func NotContainsCode(err error, code string) bool {
return !ContainsCode(err, code)
}
// ChainContainsCode verifica se o código informado existe em pelo menos um nó
// da cadeia de erros (o próprio erro + todos os parents).
func ChainContainsCode(err error, code string) bool {
if err == nil || code == "" {
return false
}
var e *Err
if !As(err, &e) {
return ContainsCode(err, code)
}
for cur := e; cur != nil; cur = cur.parent {
if cur.code == code {
return true
}
}
return false
}
// ChainNotContainsCode é a negação de ChainContainsCode.
func ChainNotContainsCode(err error, code string) bool {
return !ChainContainsCode(err, code)
}
// ChainContains verifica se o target bate (via Is) com pelo menos um nó
// da cadeia de erros (o próprio erro + todos os parents).
func ChainContains(err, target error) bool {
if err == nil || target == nil {
return false
}
var e *Err
if !As(err, &e) {
return Is(err, target)
}
for cur := e; cur != nil; cur = cur.parent {
if Is(cur, target) {
return true
}
}
return false
}
// ChainNotContains é a negação de ChainContains.
func ChainNotContains(err, target error) bool {
return !ChainContains(err, target)
}
func Contains(errs []error, target error) bool {
if len(errs) == 0 || target == nil {
return false
}
for _, err := range errs {
if Is(err, target) {
return true
}
}
return false
}
func NotContains(errs []error, target error) bool {
return !Contains(errs, target)
}
func Only(errs []error, target error) bool {
if len(errs) == 0 || target == nil {
return false
}
for _, err := range errs {
if IsNot(err, target) {
return false
}
}
return true
}
func NotOnly(errs []error, target error) bool {
return !Only(errs, target)
}
func As(err error, target any) bool {
if err == nil || target == nil {
return false
}
if t, ok := target.(**Err); ok {
extracted, parsed := extract(err, 3)
if parsed == nil {
return false
}
if extracted {
*t = parsed
}
return extracted
}
if t, ok := target.(*Err); ok {
extracted, parsed := extract(err, 3)
if extracted && parsed != nil {
*t = *parsed
}
return extracted
}
if isValidAsTarget(target) {
return errors.As(err, target)
}
return false
}
func Wrap(err error) *Err {
if err == nil {
return nil
}
_, e := extract(err, 3)
return e
}
func WrapWithExtracted(err error) (bool, *Err) {
if err == nil {
return false, nil
}
return extract(err, 3)
}
func Parse(v any) (bool, *Err, error) {
if v == nil {
return false, nil, nil
}
s, err := toStringWithErr(v)
if err != nil {
return false, nil, err
}
extracted, e := extract(errors.New(s), 3)
return extracted, e, nil
}
func Inherit(err error, msg ...any) *Err {
if err == nil {
return nil
}
e := NewWithSkipCaller(2, msg...)
extracted, parent := extract(err, 2)
e.parent = parent
if e.Message() == "<empty>" {
e.message = parent.message
}
if extracted {
e.code = parent.code
e.metadata = parent.metadata
}
return e
}
func Inheritf(err error, format string, msg ...any) *Err {
if err == nil {
return nil
}
e := NewWithSkipCallerf(2, format, msg...)
extracted, parent := extract(err, 2)
e.parent = parent
if e.Message() == "<empty>" {
e.message = parent.message
}
if extracted {
e.code = parent.code
e.metadata = parent.metadata
}
return e
}
func InheritWithSkipCaller(err error, skipCaller int, msg ...any) *Err {
if err == nil {
return nil
}
e := NewWithSkipCaller(skipCaller+1, msg...)
extracted, parent := extract(err, skipCaller+1)
e.parent = parent
if e.Message() == "<empty>" {
e.message = parent.message
}
if extracted {
e.code = parent.code
e.metadata = parent.metadata
}
return e
}
func InheritWithCode(err error, code string, msg ...any) *Err {
if err == nil {
return nil
}
e := NewWithCode(code, msg...)
extracted, parent := extract(err, 2)
e.parent = parent
if e.Message() == "<empty>" {
e.message = parent.message
}
if extracted {
e.metadata = parent.metadata
}
return e
}
func InheritWithSkipCallerf(err error, skipCaller int, format string, msg ...any) *Err {
if err == nil {
return nil
}
e := NewWithSkipCallerf(skipCaller+1, format, msg...)
extracted, parent := extract(err, skipCaller+1)
e.parent = parent
if e.Message() == "<empty>" {
e.message = parent.message
}
if extracted {
e.code = parent.code
e.metadata = parent.metadata
}
return e
}
func InheritWithAll(err error, skipCaller int, code string, metadata map[string]any, msg ...any) *Err {
if err == nil {
return nil
}
e := NewWithAll(skipCaller+1, code, metadata, msg...)
extracted, parent := extract(err, skipCaller+1)
e.parent = parent
if e.Message() == "<empty>" {
e.message = parent.message
}
if extracted {
for k, v := range parent.metadata {
if _, exists := e.metadata[k]; !exists {
e.metadata[k] = v
}
}
}
return e
}
func InheritWithSkipCallerAndCode(err error, skipCaller int, code string, msg ...any) *Err {
if err == nil {
return nil
}
e := NewWithSkipCallerAndCode(skipCaller+1, code, msg...)
extracted, parent := extract(err, skipCaller+1)
e.parent = parent
if e.Message() == "<empty>" {
e.message = parent.message
}
if extracted {
e.metadata = parent.metadata
}
return e
}
func InheritAsSlice(err error, msg ...any) []error {
if err == nil {
return nil
}
return []error{Inherit(err, msg...)}
}
func InheritAsSlicef(err error, format string, msg ...any) []error {
if err == nil {
return nil
}
return []error{Inheritf(err, format, msg...)}
}
func InheritWithSkipCallerAsSlice(err error, skipCaller int, msg ...any) []error {
if err == nil {
return nil
}
return []error{InheritWithSkipCaller(err, skipCaller, msg...)}
}
func InheritWithCodeAsSlice(err error, code string, msg ...any) []error {
if err == nil {
return nil
}
return []error{InheritWithCode(err, code, msg...)}
}
func InheritWithSkipCallerAsSlicef(err error, skipCaller int, format string, msg ...any) []error {
if err == nil {
return nil
}
return []error{InheritWithSkipCallerf(err, skipCaller, format, msg...)}
}
func InheritWithAllAsSlice(err error, skipCaller int, code string, metadata map[string]any, msg ...any) []error {
if err == nil {
return nil
}
return []error{InheritWithAll(err, skipCaller, code, metadata, msg...)}
}
func InheritWithSkipCallerAndCodeAsSlice(err error, skipCaller int, code string, msg ...any) []error {
if err == nil {
return nil
}
return []error{InheritWithSkipCallerAndCode(err, skipCaller, code, msg...)}
}
// Chain builds an ordered parent chain from a variadic list of errors.
// The first error is the root; each subsequent error becomes a deeper parent.
// Returns nil if no errors are provided.
func Chain(errs ...error) *Err {
return inheritChainFromSlice(errs)
}
// ChainFromSlice builds an ordered parent chain from a slice of errors.
// The first error is the root; each subsequent error becomes a deeper parent.
// Returns nil if the slice is empty.
func ChainFromSlice(errs []error) *Err {
return inheritChainFromSlice(errs)
}
// InheritFromSlice builds an ordered parent chain from a slice of errors.
// When msg is provided, a new root *Err wraps the chain with that message.
// When msg is omitted, the chain itself is returned directly — the first error in the slice is the root.
// Returns nil if the slice is empty.
func InheritFromSlice(errs []error, msg ...any) *Err {
if len(errs) == 0 {
return nil
}
chain := inheritChainFromSlice(errs)
if buildMessage(msg...) == "<empty>" {
return chain
}
e := NewWithSkipCaller(2, msg...)
e.parent = chain
return e
}
// InheritFromSlicef is the format-string variant of InheritFromSlice.
func InheritFromSlicef(errs []error, format string, msg ...any) *Err {
if len(errs) == 0 {
return nil
}
e := NewWithSkipCallerf(2, format, msg...)
e.parent = inheritChainFromSlice(errs)
return e
}
// InheritFromSliceWithCode is the code variant of InheritFromSlice.
// When msg is omitted, the chain is returned with the code applied to the root node.
func InheritFromSliceWithCode(errs []error, code string, msg ...any) *Err {
if len(errs) == 0 {
return nil
}
chain := inheritChainFromSlice(errs)
if buildMessage(msg...) == "<empty>" {
chain.code = code
return chain
}
e := NewWithSkipCallerAndCode(2, code, msg...)
e.parent = chain
return e
}
// InheritFromSliceWithCodef is the code and format-string variant of InheritFromSlice.
func InheritFromSliceWithCodef(errs []error, code, format string, msg ...any) *Err {
if len(errs) == 0 {
return nil
}
e := NewWithSkipCallerAndCodef(2, code, format, msg...)
e.parent = inheritChainFromSlice(errs)
return e
}
// InheritFromSliceWithAll is the skipCaller, code and metadata variant of InheritFromSlice.
// When msg is omitted, the chain is returned with code and metadata applied to the root node.
func InheritFromSliceWithAll(errs []error, skipCaller int, code string, metadata map[string]any, msg ...any) *Err {
if len(errs) == 0 {
return nil
}
chain := inheritChainFromSlice(errs)
if buildMessage(msg...) == "<empty>" {
chain.code = code
chain.metadata = metadata
return chain
}
e := NewWithAll(skipCaller+1, code, metadata, msg...)
e.parent = chain
return e
}
// InheritFromSliceWithAllf is the skipCaller, code, metadata and format-string variant of InheritFromSlice.
func InheritFromSliceWithAllf(errs []error, skipCaller int, code string, metadata map[string]any, format string, msg ...any) *Err {
if len(errs) == 0 {
return nil
}
e := NewWithAllf(skipCaller+1, code, metadata, format, msg...)
e.parent = inheritChainFromSlice(errs)
return e
}
// InheritFromSliceWithSkipCaller is the custom skipCaller variant of InheritFromSlice.
// When msg is omitted, the chain itself is returned directly.
func InheritFromSliceWithSkipCaller(errs []error, skipCaller int, msg ...any) *Err {
if len(errs) == 0 {
return nil
}
chain := inheritChainFromSlice(errs)
if buildMessage(msg...) == "<empty>" {
return chain
}
e := NewWithSkipCaller(skipCaller+1, msg...)
e.parent = chain
return e
}
// InheritFromSliceWithSkipCallerf is the skipCaller and format-string variant of InheritFromSlice.
func InheritFromSliceWithSkipCallerf(errs []error, skipCaller int, format string, msg ...any) *Err {
if len(errs) == 0 {
return nil
}
e := NewWithSkipCallerf(skipCaller+1, format, msg...)
e.parent = inheritChainFromSlice(errs)
return e
}
// InheritFromSliceWithSkipCallerAndCode is the skipCaller and code variant of InheritFromSlice.
// When msg is omitted, the chain is returned with the code applied to the root node.
func InheritFromSliceWithSkipCallerAndCode(errs []error, skipCaller int, code string, msg ...any) *Err {
if len(errs) == 0 {
return nil
}
chain := inheritChainFromSlice(errs)
if buildMessage(msg...) == "<empty>" {
chain.code = code
return chain
}
e := NewWithSkipCallerAndCode(skipCaller+1, code, msg...)
e.parent = chain
return e
}
// InheritFromSliceWithSkipCallerAndCodef is the skipCaller, code and format-string variant of InheritFromSlice.
func InheritFromSliceWithSkipCallerAndCodef(errs []error, skipCaller int, code, format string, msg ...any) *Err {
if len(errs) == 0 {
return nil
}
e := NewWithSkipCallerAndCodef(skipCaller+1, code, format, msg...)
e.parent = inheritChainFromSlice(errs)
return e
}
func Join(errs []error, sep string) *Err {
if len(errs) == 0 {
return nil
}
file, line, funcName := callerInfos(1)
return &Err{
file: file,
line: line,
funcName: funcName,
message: JoinToString(errs, sep),
stack: buildDebugStack(),
}
}
func JoinInherit(errs []error, sep string, msg ...any) error {
if errs == nil {
return nil
}
return Inherit(Join(errs, sep), msg...)
}
func JoinInheritf(errs []error, sep, format string, msg ...any) *Err {
if errs == nil {
return nil
}
return Inheritf(Join(errs, sep), format, msg...)
}
func JoinInheritAsSlice(errs []error, sep string, msg ...any) []error {
if errs == nil {
return nil
}
return InheritAsSlice(Join(errs, sep), msg...)
}
func JoinInheritAsSlicef(errs []error, sep, format string, msg ...any) []error {
if errs == nil {
return nil
}
return InheritAsSlicef(Join(errs, sep), format, msg...)
}
func JoinInheritWithSkipCaller(errs []error, sep string, skipCaller int, msg ...any) *Err {
if errs == nil {
return nil
}
return InheritWithSkipCaller(Join(errs, sep), skipCaller, msg...)
}
func JoinInheritWithCode(errs []error, sep, code string, msg ...any) *Err {
if errs == nil {
return nil
}
return InheritWithCode(Join(errs, sep), code, msg...)
}
func JoinInheritWithSkipCallerf(errs []error, sep string, skipCaller int, format string, msg ...any) *Err {
if errs == nil {
return nil
}
return InheritWithSkipCallerf(Join(errs, sep), skipCaller, format, msg...)
}
func JoinInheritWithAll(errs []error, sep string, skipCaller int, code string, metadata map[string]any, msg ...any) *Err {
if errs == nil {
return nil
}
return InheritWithAll(Join(errs, sep), skipCaller, code, metadata, msg...)
}
func JoinInheritWithSkipCallerAndCode(errs []error, sep string, skipCaller int, code string, msg ...any) *Err {
if errs == nil {
return nil
}
return InheritWithSkipCallerAndCode(Join(errs, sep), skipCaller, code, msg...)
}
// JoinToString concatena as mensagens dos erros da fatia separadas por sep.
// Erros nil ou sem mensagem são ignorados silenciosamente.
func JoinToString(errs []error, sep string) (result string) {
if len(errs) == 0 {
return ""
}
for i, err := range errs {
dt := Wrap(err)
if dt != nil {
result += dt.message
}
if i < len(errs)-1 {
result += sep
}
}
return result
}
func extract(err error, skipCaller int) (bool, *Err) {
if err == nil {
return false, nil
}
var e *Err
if errors.As(err, &e) {
return true, e
}
rg := compiledRegex
matches := rg.FindStringSubmatch(err.Error())
if len(matches) == 0 {
file, line, funcName := callerInfos(skipCaller + 1)
return false, &Err{
file: file,
line: line,
funcName: funcName,
message: buildMessage(err.Error()),
stack: buildDebugStack(),
}
}
stackRaw := matches[7]
// Separate the own stack from any [INHERITED BY] blocks
ownStack, inheritedParts := splitInheritedBlocks(stackRaw)
e = &Err{
file: matches[2],
line: matches[3],
funcName: matches[4],
message: matches[5],
stack: []byte(ownStack),
}
if matches[1] != "" {
e.code = matches[1]
}
if matches[6] != "" {
metaStr := matches[6]
var meta map[string]any
if err = json.Unmarshal([]byte(metaStr), &meta); err == nil {
e.metadata = meta
} else {
e.metadata = map[string]any{
"raw": metaStr,
}
}
}
// Try to extract a nested error from the message (snapshot format: [CODE]: X [MESSAGE]: Y)
if nested := parseSnapshotFromMessage(e.message); nested != nil {
e.message = nested.message
if nested.code != "" && e.code == "" {
e.code = nested.code
}
if nested.code != "" && e.code != nested.code {
// The message contained a different code — preserve it as a parent
nested.file = e.file
nested.line = e.line
nested.funcName = e.funcName
nested.stack = e.stack
e.parent = chainParents(nested, inheritedParts)
return true, e
}
}
// Build parent chain from [INHERITED BY] blocks
e.parent = chainParents(nil, inheritedParts)
return true, e
}
// parseSnapshotFromMessage checks if a message contains a snapshot pattern
// like "[CODE]: X [MESSAGE]: Y" and extracts it into an Err with code and message.
func parseSnapshotFromMessage(msg string) *Err {
m := compiledSnapshotRegex.FindStringSubmatch(msg)
if len(m) == 0 {
return nil
}
return &Err{
code: m[1],
message: m[2],
}
}
// splitInheritedBlocks splits a stack string at each [INHERITED BY] separator,
// returning the own stack (before the first separator) and a slice of the
// inherited error strings (each one is a full Error() representation).
func splitInheritedBlocks(stack string) (string, []string) {
sep := "----------------\n\t\t|\t[INHERITED BY]: "
parts := strings.SplitN(stack, sep, 2)
if len(parts) == 1 {
return stack, nil
}
ownStack := parts[0]
rest := parts[1]
var inherited []string
for {
idx := strings.Index(rest, sep)
if idx < 0 {
inherited = append(inherited, rest)
break
}
inherited = append(inherited, rest[:idx])
rest = rest[idx+len(sep):]
}
return ownStack, inherited
}
// chainParents builds a linked parent chain from an optional head Err and
// a slice of inherited error strings. Each string is parsed via extract.
func chainParents(head *Err, inheritedParts []string) *Err {
// Parse all inherited parts into Err nodes
var nodes []*Err
if head != nil {
nodes = append(nodes, head)
}
for _, part := range inheritedParts {
_, parsed := extract(errors.New(part), 3)
if parsed != nil {
nodes = append(nodes, parsed)
}
}
if len(nodes) == 0 {
return nil
}
// Link them: first is the direct parent, last is the deepest ancestor
for i := 0; i < len(nodes)-1; i++ {
nodes[i].parent = nodes[i+1]
}
return nodes[0]
}
func isValidAsTarget(target any) bool {
rv := reflect.ValueOf(target)
if rv.Kind() != reflect.Ptr || rv.IsNil() {
return false
}
elem := rv.Type().Elem()
errorType := reflect.TypeOf((*error)(nil)).Elem()
return elem.Implements(errorType) || elem.Kind() == reflect.Interface
}
// inheritChainFromSlice builds a parent chain from a slice of errors.
// The first error in the slice sits at the top of the chain; the last is the deepest parent.
// Returns nil if the slice is empty.
func inheritChainFromSlice(errs []error) *Err {
if len(errs) == 0 {
return nil
}
_, chain := extract(errs[len(errs)-1], 3)
for i := len(errs) - 2; i >= 0; i-- {
_, node := extract(errs[i], 3)
node.parent = chain
chain = node
}
return chain
}