-
-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy patherror.go
More file actions
934 lines (794 loc) · 25.3 KB
/
error.go
File metadata and controls
934 lines (794 loc) · 25.3 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
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
//nolint:bodyclose
package oops
import (
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
"net/http/httputil"
"runtime"
"strings"
"sync"
"time"
"github.com/samber/lo"
)
// Global configuration variables that control the behavior of error handling.
var (
// SourceFragmentsHidden controls whether source code fragments are included in error output.
// When true, source code context around error locations is hidden to reduce output size.
SourceFragmentsHidden = true
// DereferencePointers controls whether pointer values in error context are automatically
// dereferenced when converting to map representations. This can be useful for logging
// but may cause issues with nil pointers.
DereferencePointers = true
// Local specifies the timezone used for error timestamps. Defaults to UTC.
Local *time.Location = time.UTC
// AutoTraceID controls whether a ULID-based trace ID is automatically generated
// when an error is created without an explicit trace.
//
// Note: this flag does not integrate with or take precedence over external tracing
// systems (OpenTelemetry, HTTP middleware, etc.). Trace IDs from those systems must
// still be injected explicitly via .Trace("id").
//
// Generating a trace ID on every error creation has a non-negligible cost (ULID
// generation + allocation). Consider setting this to false at program start when
// trace IDs are always provided by an external system.
AutoTraceID = true
)
// Type assertions to ensure OopsError implements required interfaces.
var (
_ error = (*OopsError)(nil)
_ slog.LogValuer = (*OopsError)(nil)
)
// OopsErrorLayer holds the attributes of a single layer in an error chain,
// as returned by Layers(). Every field reflects the value set at that specific
// wrapping level only — no chain traversal is performed. Fields that were not
// set on that layer carry their zero value.
type OopsErrorLayer struct {
// Core error information
Code any
Time time.Time
Duration time.Duration
// Contextual information
Domain string
Tags []string
Context map[string]any
// Tracing information
Trace string
Span string
// Developer-facing information
Hint string
Public string
Owner string
// User and tenant information
UserID string
UserData map[string]any
TenantID string
TenantData map[string]any
// HTTP request/response information
Request *http.Request
Response *http.Response
}
// outputBlock is one node in the error chain, holding pre-filtered frames.
type outputBlock struct {
err error
msg string
frames []oopsStacktraceFrame
}
// OopsError represents an enhanced error with additional contextual information.
// It implements the standard error interface while providing rich metadata for
// debugging, logging, and error handling.
type OopsError struct {
// Core error information
err error // The underlying error being wrapped
msg string // Additional error message
code any // Machine-readable error code/slug (any JSON/log-friendly type)
time time.Time // When the error occurred
duration time.Duration // Duration associated with the error
// Contextual information
domain string // Feature category or domain (e.g., "auth", "database")
tags []string // Tags for categorizing the error
context map[string]any // Key-value pairs for additional context
// Tracing information
trace string // Transaction/trace/correlation ID
traceAutoGenerated bool // true when trace was set by the library, false when set explicitly by the caller
span string // Current span identifier
// Developer-facing information
hint string // Debugging hint for developers
public string // User-safe error message
owner string // Team/person responsible for handling this error
// User and tenant information
userID string // User identifier
userData map[string]any // User-related data
tenantID string // Tenant identifier
tenantData map[string]any // Tenant-related data
// HTTP request/response information
req *lo.Tuple2[*http.Request, bool] // HTTP request with body inclusion flag
res *lo.Tuple2[*http.Response, bool] // HTTP response with body inclusion flag
// Stack trace information
stacktrace *oopsStacktrace // Captured stack trace
callerSkip int // Number of additional frames to skip when capturing stack trace
// Lazily computed filtered frame blocks shared by Stacktrace() and Sources().
// Both are pointers so that value copies of OopsError share the same state;
// cacheOnce as a pointer also avoids the go vet copylocks check.
cacheOnce *sync.Once
cacheBlocks *[]outputBlock
}
// Unwrap returns the underlying error that this OopsError wraps.
// This method implements the errors.Wrapper interface.
func (o OopsError) Unwrap() error {
return o.err
}
// toLayer converts the current OopsError into an OopsErrorLayer containing
// only the attributes set at this specific layer. No chain traversal is performed.
// Map values are processed the same way as in ToMap: lazy functions are evaluated
// and pointer values are dereferenced.
func (o OopsError) toLayer() *OopsErrorLayer {
layer := &OopsErrorLayer{
Code: o.code,
Duration: o.duration,
Domain: o.domain,
Tags: o.tags,
Context: dereferencePointers(lazyMapEvaluation(o.context)),
Trace: o.trace,
Span: o.span,
Hint: o.hint,
Public: o.public,
Owner: o.owner,
UserID: o.userID,
UserData: dereferencePointers(lazyMapEvaluation(o.userData)),
TenantID: o.tenantID,
TenantData: dereferencePointers(lazyMapEvaluation(o.tenantData)),
}
if !o.time.IsZero() {
layer.Time = o.time.In(Local)
}
if o.req != nil {
layer.Request = o.req.A
}
if o.res != nil {
layer.Response = o.res.A
}
return layer
}
// Layers returns a slice of all OopsError layers in the error chain,
// from outermost to innermost. Each element represents one wrapping layer
// with its own attributes, allowing callers to inspect or select attributes
// from any layer rather than only the deepest one.
//
// Only OopsError layers are included; non-OopsError errors in the chain
// (e.g. a plain fmt.Errorf or sentinel error at the root) are skipped.
// Use Unwrap() on the innermost layer to access the underlying error.
func (o OopsError) Layers() []*OopsErrorLayer {
var layers []*OopsErrorLayer
recursive(o, func(e OopsError) bool {
layers = append(layers, e.toLayer())
return true
})
return layers
}
// Is implements the errors.Is interface.
//
// OopsError contains non-comparable fields (maps, slices), so the default
// equality check performed by errors.Is would panic at runtime. Identity is
// therefore established via the span ID, which is unique per error instance.
//
// Note: errors.Is is designed for sentinel value matching (e.g. io.EOF).
// To check whether an error in the chain is an OopsError, prefer errors.As
// or oops.AsOops instead.
func (o OopsError) Is(err error) bool {
if other, ok := err.(OopsError); ok && o.span == other.span {
return true
}
return errors.Is(o.err, err)
}
// Error returns the error message without additional context.
// This method implements the error interface.
// If the error wraps another error, it returns "message: wrapped_error".
// Otherwise, it returns just the message.
func (o OopsError) Error() string {
if o.err != nil {
if o.msg == "" {
return o.err.Error()
}
return o.msg + ": " + o.err.Error()
}
return o.msg
}
// Code returns the error code from the deepest error in the chain.
// Error codes are machine-readable identifiers that can be used for
// programmatic error handling and cross-service error correlation.
func (o OopsError) Code() any {
return getDeepestErrorCode(o)
}
func getDeepestErrorCode(err OopsError) any {
if err.err == nil {
return err.code
}
if child, ok := AsOops(err.err); ok {
deepest := getDeepestErrorCode(child)
if deepest != nil {
return deepest
}
}
return err.code
}
// Time returns the timestamp when the error occurred.
// Returns the time from the deepest error in the chain.
func (o OopsError) Time() time.Time {
return getDeepestErrorAttribute(
o,
func(e OopsError) time.Time {
return e.time
},
)
}
// Duration returns the duration associated with the error.
// Returns the duration from the deepest error in the chain.
func (o OopsError) Duration() time.Duration {
return getDeepestErrorAttribute(
o,
func(e OopsError) time.Duration {
return e.duration
},
)
}
// Domain returns the domain/feature category of the error.
// Returns the domain from the deepest error in the chain.
func (o OopsError) Domain() string {
return getDeepestErrorAttribute(
o,
func(e OopsError) string {
return e.domain
},
)
}
// Tags returns all unique tags from the error chain.
// Tags are merged from all errors in the chain and deduplicated.
func (o OopsError) Tags() []string {
tags := make([]string, 0, 8) // reasonable initial capacity for tags
recursive(o, func(e OopsError) bool {
tags = append(tags, e.tags...)
return true
})
return lo.Uniq(tags)
}
// HasTag checks if the error or any of its wrapped errors contain the specified tag.
// This is useful for conditional error handling based on error categories.
func (o OopsError) HasTag(tag string) bool {
found := false
recursive(o, func(e OopsError) bool {
if lo.Contains(e.tags, tag) {
found = true
}
return !found
})
return found
}
// Context returns a flattened key-value context map from the error chain.
// Context from all errors in the chain is merged, with later errors taking precedence.
// Pointer values are dereferenced if DereferencePointers is enabled.
// Lazy evaluation functions are executed to get their values.
func (o OopsError) Context() map[string]any {
return dereferencePointers(
lazyMapEvaluation(
mergeNestedErrorMap(
o,
func(e OopsError) map[string]any {
return e.context
},
),
),
)
}
// Trace returns the transaction/trace/correlation ID.
// An ID is auto-generated at error creation time if none was set explicitly.
//
// Explicit traces (set via .Trace("id")) always take precedence over
// auto-generated ones, regardless of chain depth. Among traces of the same
// kind, the deepest one in the chain wins.
func (o OopsError) Trace() string {
return getTraceFromChain(o)
}
// getTraceFromChain walks the full error chain and returns the deepest
// explicit trace, falling back to the deepest auto-generated trace.
func getTraceFromChain(err OopsError) string {
explicit := ""
auto := ""
// recursive visits outer→inner, so each write overwrites with a deeper value.
recursive(err, func(e OopsError) bool {
if e.trace == "" {
return true
}
if e.traceAutoGenerated {
auto = e.trace
} else {
explicit = e.trace
}
return true
})
if explicit != "" {
return explicit
}
return auto
}
// Span returns the current span identifier.
// Unlike other attributes, span returns the current error's span, not the deepest one.
func (o OopsError) Span() string {
return o.span
}
// Hint returns a debugging hint for resolving the error.
// Returns the hint from the deepest error in the chain.
func (o OopsError) Hint() string {
return getDeepestErrorAttribute(
o,
func(e OopsError) string {
return e.hint
},
)
}
// Public returns a user-safe error message.
// Returns the public message from the deepest error in the chain.
func (o OopsError) Public() string {
return getDeepestErrorAttribute(
o,
func(e OopsError) string {
return e.public
},
)
}
// Owner returns the name/email of the person/team responsible for handling this error.
// Returns the owner from the deepest error in the chain.
func (o OopsError) Owner() string {
return getDeepestErrorAttribute(
o,
func(e OopsError) string {
return e.owner
},
)
}
// User returns the user ID and associated user data.
// Returns the user information from the deepest error in the chain.
func (o OopsError) User() (string, map[string]any) {
userID := getDeepestErrorAttribute(
o,
func(e OopsError) string {
return e.userID
},
)
userData := dereferencePointers(
lazyMapEvaluation(
mergeNestedErrorMap(
o,
func(e OopsError) map[string]any {
return e.userData
},
),
),
)
return userID, userData
}
// Tenant returns the tenant ID and associated tenant data.
// Returns the tenant information from the deepest error in the chain.
func (o OopsError) Tenant() (string, map[string]any) {
tenantID := getDeepestErrorAttribute(
o,
func(e OopsError) string {
return e.tenantID
},
)
tenantData := dereferencePointers(
lazyMapEvaluation(
mergeNestedErrorMap(
o,
func(e OopsError) map[string]any {
return e.tenantData
},
),
),
)
return tenantID, tenantData
}
// Request returns the associated HTTP request.
// Returns the request from the deepest error in the chain.
func (o OopsError) Request() *http.Request {
t := o.request()
if t != nil {
return t.A
}
return nil
}
// request returns the internal request tuple with body inclusion flag.
func (o OopsError) request() *lo.Tuple2[*http.Request, bool] {
return getDeepestErrorAttribute(
o,
func(e OopsError) *lo.Tuple2[*http.Request, bool] {
return e.req
},
)
}
// Response returns the associated HTTP response.
// Returns the response from the deepest error in the chain.
func (o OopsError) Response() *http.Response {
t := o.response()
if t != nil {
return t.A
}
return nil
}
// response returns the internal response tuple with body inclusion flag.
func (o OopsError) response() *lo.Tuple2[*http.Response, bool] {
return getDeepestErrorAttribute(
o,
func(e OopsError) *lo.Tuple2[*http.Response, bool] {
return e.res
},
)
}
// rawBlocksWithCache returns the filtered frame blocks shared by Stacktrace and Sources.
// When a cache is present the traversal runs at most once; subsequent calls return
// the cached slice directly.
func (o OopsError) rawBlocksWithCache() []outputBlock {
if o.cacheOnce == nil || o.cacheBlocks == nil {
return o.rawBlocks()
}
o.cacheOnce.Do(func() {
*o.cacheBlocks = o.rawBlocks()
})
return *o.cacheBlocks
}
// rawBlocks performs the actual recursive frame traversal and applyFrameSkip filtering.
func (o OopsError) rawBlocks() []outputBlock {
var blocks []outputBlock
recursive(o, func(e OopsError) bool {
if e.stacktrace != nil {
filteredFrames := applyFrameSkip(e.stacktrace.frames)
if len(filteredFrames) > 0 {
blocks = append(blocks, outputBlock{e.err, e.msg, filteredFrames})
}
}
return true
})
return blocks
}
// Stacktrace returns a formatted string representation of the error's stack trace.
// The stack trace shows the call hierarchy leading to the error, excluding
// frames from the Go standard library and this package.
// The stacktrace is basically written from the bottom to the top, in order to dedup frames.
// It support recursive code.
func (o OopsError) Stacktrace() string {
blocks := o.rawBlocksWithCache()
if len(blocks) == 0 {
return ""
}
stBlocks := make([]lo.Tuple3[error, string, []oopsStacktraceFrame], len(blocks))
for i, b := range blocks {
stBlocks[i] = lo.T3(b.err, b.msg, b.frames)
}
return "Oops: " + strings.Join(framesToStacktraceBlocks(stBlocks), "\nThrown: ")
}
// StackFrames returns the raw stack frames as runtime.Frame objects.
// This is useful for custom stack trace formatting or analysis.
func (o OopsError) StackFrames() []runtime.Frame {
if o.stacktrace == nil {
return nil
}
filtered := applyFrameSkip(o.stacktrace.frames)
frames := make([]runtime.Frame, 0, len(filtered))
for _, f := range filtered {
frames = append(frames, runtime.Frame{
PC: f.pc,
File: f.file,
Line: f.line,
Function: f.function,
})
}
return frames
}
// Sources returns formatted source code fragments around the error location.
// This provides context about the code that caused the error, which is
// particularly useful for debugging. The output includes line numbers and
// highlights the exact line where the error occurred.
func (o OopsError) Sources() string {
blocks := o.rawBlocksWithCache()
if len(blocks) == 0 {
return ""
}
srcBlocks := make([]lo.Tuple2[string, *oopsStacktrace], len(blocks))
for i, b := range blocks {
srcBlocks[i] = lo.T2(b.msg, &oopsStacktrace{frames: b.frames})
}
return "Oops: " + strings.Join(framesToSourceBlocks(srcBlocks), "\n\nThrown: ")
}
// LogValuer returns a slog.Value representation of the error.
// This method implements the slog.LogValuer interface for structured logging.
//
// Deprecated: Use LogValue instead.
func (o OopsError) LogValuer() slog.Value {
return o.LogValue()
}
// LogValue returns a slog.Value representation of the error for structured logging.
// This method implements the slog.LogValuer interface and provides a flattened
// representation of the error's context and metadata suitable for logging systems.
func (o OopsError) LogValue() slog.Value { //nolint:gocyclo
attrs := make([]slog.Attr, 0, 16)
attrs = append(attrs, slog.String("message", o.msg))
if err := o.Error(); err != "" {
attrs = append(attrs, slog.String("err", err))
}
if code := o.Code(); code != nil {
attrs = append(attrs, slog.Any("code", code))
}
if t := o.Time(); t != (time.Time{}) {
attrs = append(attrs, slog.Time("time", t.In(Local)))
}
if duration := o.Duration(); duration != 0 {
attrs = append(attrs, slog.Duration("duration", duration))
}
if domain := o.Domain(); domain != "" {
attrs = append(attrs, slog.String("domain", domain))
}
if tags := o.Tags(); len(tags) > 0 {
attrs = append(attrs, slog.Any("tags", tags))
}
if trace := o.Trace(); trace != "" {
attrs = append(attrs, slog.String("trace", trace))
}
// if span := o.Span(); span != "" {
// attrs = append(attrs, slog.String("span", span))
// }
if hint := o.Hint(); hint != "" {
attrs = append(attrs, slog.String("hint", hint))
}
if public := o.Public(); public != "" {
attrs = append(attrs, slog.String("public", public))
}
if owner := o.Owner(); owner != "" {
attrs = append(attrs, slog.String("owner", owner))
}
if context := o.Context(); len(context) > 0 {
attrs = append(attrs,
slog.Group(
"context",
lo.ToAnySlice(
lo.MapToSlice(context, slog.Any),
)...,
),
)
}
if userID, userData := o.User(); userID != "" || len(userData) > 0 {
userPayload := []slog.Attr{}
if userID != "" {
userPayload = append(userPayload, slog.String("id", userID))
userPayload = append(
userPayload,
lo.MapToSlice(userData, slog.Any)...,
)
}
attrs = append(attrs, slog.Group("user", lo.ToAnySlice(userPayload)...))
}
if tenantID, tenantData := o.Tenant(); tenantID != "" || len(tenantData) > 0 {
tenantPayload := []slog.Attr{}
if tenantID != "" {
tenantPayload = append(tenantPayload, slog.String("id", tenantID))
tenantPayload = append(
tenantPayload,
lo.MapToSlice(tenantData, slog.Any)...,
)
}
attrs = append(attrs, slog.Group("tenant", lo.ToAnySlice(tenantPayload)...))
}
if req := o.request(); req != nil {
dump, e := httputil.DumpRequestOut(req.A, req.B)
if e == nil {
attrs = append(attrs, slog.String("request", string(dump)))
}
}
if res := o.response(); res != nil {
dump, e := httputil.DumpResponse(res.A, res.B)
if e == nil {
attrs = append(attrs, slog.String("response", string(dump)))
}
}
if stacktrace := o.Stacktrace(); stacktrace != "" {
attrs = append(attrs, slog.String("stacktrace", stacktrace))
}
if sources := o.Sources(); sources != "" && !SourceFragmentsHidden {
attrs = append(attrs, slog.String("sources", sources))
}
return slog.GroupValue(attrs...)
}
// ToMap converts the error to a map representation suitable for JSON serialization.
// This method provides a flattened view of all error attributes and is useful
// for logging, debugging, and cross-service error transmission.
func (o OopsError) ToMap() map[string]any { //nolint:gocyclo
payload := map[string]any{}
if err := o.Error(); err != "" {
payload["error"] = err
}
if code := o.Code(); code != nil {
payload["code"] = code
}
if t := o.Time(); t != (time.Time{}) {
payload["time"] = t.In(Local)
}
if duration := o.Duration(); duration != 0 {
payload["duration"] = duration.String()
}
if domain := o.Domain(); domain != "" {
payload["domain"] = domain
}
if tags := o.Tags(); len(tags) > 0 {
payload["tags"] = tags
}
if context := o.Context(); len(context) > 0 {
payload["context"] = context
}
if trace := o.Trace(); trace != "" {
payload["trace"] = trace
}
// if span := o.Span(); span != "" {
// payload["span"] = span
// }
if hint := o.Hint(); hint != "" {
payload["hint"] = hint
}
if public := o.Public(); public != "" {
payload["public"] = public
}
if owner := o.Owner(); owner != "" {
payload["owner"] = owner
}
if userID, userData := o.User(); userID != "" || len(userData) > 0 {
user := lo.Assign(map[string]any{}, userData)
if userID != "" {
user["id"] = userID
}
payload["user"] = user
}
if tenantID, tenantData := o.Tenant(); tenantID != "" || len(tenantData) > 0 {
tenant := lo.Assign(map[string]any{}, tenantData)
if tenantID != "" {
tenant["id"] = tenantID
}
payload["tenant"] = tenant
}
if req := o.request(); req != nil {
dump, e := httputil.DumpRequestOut(req.A, req.B)
if e == nil {
payload["request"] = string(dump)
}
}
if res := o.response(); res != nil {
dump, e := httputil.DumpResponse(res.A, res.B)
if e == nil {
payload["response"] = string(dump)
}
}
if stacktrace := o.Stacktrace(); stacktrace != "" {
payload["stacktrace"] = stacktrace
}
if sources := o.Sources(); sources != "" && !SourceFragmentsHidden {
payload["sources"] = sources
}
return payload
}
// MarshalJSON implements the json.Marshaler interface.
// This allows OopsError to be directly serialized to JSON.
func (o OopsError) MarshalJSON() ([]byte, error) {
return json.Marshal(o.ToMap())
}
// Format implements the fmt.Formatter interface for custom formatting.
// Supports the following format verbs:
// - %v: standard error message
// - %+v: verbose format with stack trace and context
// - %#v: Go syntax representation.
func (o OopsError) Format(s fmt.State, verb rune) {
switch verb {
case 'v':
if s.Flag('+') {
// Verbose format with stack trace and context
_, _ = fmt.Fprint(s, o.formatVerbose())
} else {
// Standard format
_, _ = fmt.Fprint(s, o.formatSummary())
}
case 's':
_, _ = fmt.Fprint(s, o.Error())
case 'q':
_, _ = fmt.Fprintf(s, "%q", o.Error())
default:
_, _ = fmt.Fprint(s, o.formatSummary())
}
}
// formatVerbose returns a detailed string representation of the error
// including all context, stack trace, and source code fragments.
func (o *OopsError) formatVerbose() string { //nolint:gocyclo
var output strings.Builder
_, _ = fmt.Fprintf(&output, "Oops: %s\n", o.Error())
if code := o.Code(); code != nil {
_, _ = fmt.Fprintf(&output, "Code: %v\n", code)
}
if t := o.Time(); t != (time.Time{}) {
_, _ = fmt.Fprintf(&output, "Time: %s\n", t.In(Local))
}
if duration := o.Duration(); duration != 0 {
_, _ = fmt.Fprintf(&output, "Duration: %s\n", duration.String())
}
if domain := o.Domain(); domain != "" {
_, _ = fmt.Fprintf(&output, "Domain: %s\n", domain)
}
if tags := o.Tags(); len(tags) > 0 {
_, _ = fmt.Fprintf(&output, "Tags: %s\n", strings.Join(tags, ", "))
}
if trace := o.Trace(); trace != "" {
_, _ = fmt.Fprintf(&output, "Trace: %s\n", trace)
}
// if span := o.Span(); span != "" {
// _, _ = fmt.Fprintf(&output, "Span: %s\n", span)
// }
if hint := o.Hint(); hint != "" {
_, _ = fmt.Fprintf(&output, "Hint: %s\n", hint)
}
if owner := o.Owner(); owner != "" {
_, _ = fmt.Fprintf(&output, "Owner: %s\n", owner)
}
if context := o.Context(); len(context) > 0 {
output.WriteString("Context:\n")
for k, v := range context {
_, _ = fmt.Fprintf(&output, " * %s: %v\n", k, v)
}
}
if userID, userData := o.User(); userID != "" || len(userData) > 0 {
output.WriteString("User:\n")
if userID != "" {
_, _ = fmt.Fprintf(&output, " * id: %s\n", userID)
}
for k, v := range userData {
_, _ = fmt.Fprintf(&output, " * %s: %v\n", k, v)
}
}
if tenantID, tenantData := o.Tenant(); tenantID != "" || len(tenantData) > 0 {
output.WriteString("Tenant:\n")
if tenantID != "" {
_, _ = fmt.Fprintf(&output, " * id: %s\n", tenantID)
}
for k, v := range tenantData {
_, _ = fmt.Fprintf(&output, " * %s: %v\n", k, v)
}
}
if req := o.request(); req != nil {
dump, e := httputil.DumpRequestOut(req.A, req.B)
if e == nil {
lines := strings.Split(string(dump), "\n")
lines = lo.Map(lines, func(line string, _ int) string {
return " * " + line
})
_, _ = fmt.Fprintf(&output, "Request:\n%s\n", strings.Join(lines, "\n"))
}
}
if res := o.response(); res != nil {
dump, e := httputil.DumpResponse(res.A, res.B)
if e == nil {
lines := strings.Split(string(dump), "\n")
lines = lo.Map(lines, func(line string, _ int) string {
return " * " + line
})
_, _ = fmt.Fprintf(&output, "Response:\n%s\n", strings.Join(lines, "\n"))
}
}
if stacktrace := o.Stacktrace(); stacktrace != "" {
lines := strings.Split(stacktrace, "\n")
stacktrace = " " + strings.Join(lines, "\n ")
_, _ = fmt.Fprintf(&output, "Stacktrace:\n%s\n", stacktrace)
}
if sources := o.Sources(); sources != "" && !SourceFragmentsHidden {
_, _ = fmt.Fprintf(&output, "Sources:\n%s\n", sources)
}
return output.String()
}
// formatSummary returns a brief summary of the error for logging.
func (o *OopsError) formatSummary() string {
return o.Error()
}