-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror.go
More file actions
1403 lines (1218 loc) · 36.4 KB
/
error.go
File metadata and controls
1403 lines (1218 loc) · 36.4 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
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package errific provides enhanced error handling for Go with caller information,
// clean error wrapping, and helpful formatting methods.
//
// errific simplifies error creation by adding runtime caller metadata (file, line, function)
// to errors, making debugging easier without sacrificing clean error messages. It supports
// error chaining, formatted messages, and configurable output options including stack traces.
//
// Basic usage:
//
// var ErrProcessThing errific.Err = "error processing thing"
//
// func process() error {
// if err := validate(); err != nil {
// return ErrProcessThing.New(err)
// }
// return nil
// }
//
// The resulting error includes caller information:
//
// error processing thing [mypackage/file.go:42.process]
// validation failed [mypackage/validate.go:15.validate]
//
// Configuration options include caller position (prefix/suffix/disabled),
// layout (newline/inline), stack traces, and path trimming.
package errific
import (
"encoding/json"
"errors"
"fmt"
"runtime"
"strings"
"time"
)
// Err string type.
//
// To include runtime caller information on the error,
// one of the Err methods, other than Error(), must be called.
//
// For examples see the example tests. All examples
// demonstrate using exported errors as a recommended best
// practice because exported errors enable unit-tests that assert
// expected errors such as: assert.ErrorIs(t, err, ErrProcessThing).
type Err string
// New returns an error using Err as text with errors joined.
//
// var ErrProcessThing errific.Err = "error processing a thing"
//
// return ErrProcessThing.New(err)
func (e Err) New(errs ...error) errific {
a := make([]any, len(errs))
for i := range errs {
a[i] = errs[i]
}
caller, stack, cfg := callstack(a)
return errific{
err: e,
errs: errs,
caller: caller,
stack: stack,
cfg: cfg,
}
}
// Errorf returns an error using Err formatted as text.
// Use Errorf if your Err string itself contains fmt format specifiers.
//
// var ErrProcessThing errific.Err = "error processing thing id: '%s'"
//
// return ErrProcessThing.Errorf("abc")
func (e Err) Errorf(a ...any) errific {
caller, stack, cfg := callstack(a)
return errific{
err: fmt.Errorf(e.Error(), a...),
caller: caller,
unwrap: []error{e},
stack: stack,
cfg: cfg,
}
}
// Withf returns an error with a formatted string inline to Err as text.
//
// var ErrProcessThing errific.Err = "error processing thing"
//
// return ErrProcessThing.Withf("id: '%s'", "abc")
func (e Err) Withf(format string, a ...any) errific {
caller, stack, cfg := callstack(a)
format = e.Error() + ": " + format
return errific{
err: fmt.Errorf(format, a...),
caller: caller,
unwrap: []error{e},
stack: stack,
cfg: cfg,
}
}
// Wrapf return an error using Err as text and wraps a formatted error.
// Use Wrapf to format an error and wrap it.
//
// var ErrProcessThing errific.Err = "error processing thing"
//
// return ErrProcessThing.Wrapf("cause: %w", err)
func (e Err) Wrapf(format string, a ...any) errific {
caller, stack, cfg := callstack(a)
return errific{
err: e,
errs: []error{fmt.Errorf(format, a...)},
caller: caller,
stack: stack,
cfg: cfg,
}
}
func (e Err) Error() string {
return string(e)
}
// Forwarding methods allow calling With___ methods directly on Err without explicit New().
// These methods call New() once, then forward to the corresponding errific method.
// Chaining is efficient - New() is only called once on the first method in the chain.
//
// Example:
// err := ErrTest.WithCode("CODE1").WithHTTPStatus(400)
// // New() called once on WithCode, then WithHTTPStatus uses errific method
func (e Err) WithContext(ctx Context) errific {
return e.New().WithContext(ctx)
}
func (e Err) WithCode(code string) errific {
return e.New().WithCode(code)
}
func (e Err) WithCategory(category Category) errific {
return e.New().WithCategory(category)
}
func (e Err) WithRetryable(retryable bool) errific {
return e.New().WithRetryable(retryable)
}
func (e Err) WithRetryAfter(duration time.Duration) errific {
return e.New().WithRetryAfter(duration)
}
func (e Err) WithMaxRetries(max int) errific {
return e.New().WithMaxRetries(max)
}
func (e Err) WithHTTPStatus(status int) errific {
return e.New().WithHTTPStatus(status)
}
func (e Err) WithMCPCode(code int) errific {
return e.New().WithMCPCode(code)
}
func (e Err) WithCorrelationID(id string) errific {
return e.New().WithCorrelationID(id)
}
func (e Err) WithRequestID(id string) errific {
return e.New().WithRequestID(id)
}
func (e Err) WithUserID(id string) errific {
return e.New().WithUserID(id)
}
func (e Err) WithSessionID(id string) errific {
return e.New().WithSessionID(id)
}
func (e Err) WithHelp(text string) errific {
return e.New().WithHelp(text)
}
func (e Err) WithSuggestion(text string) errific {
return e.New().WithSuggestion(text)
}
func (e Err) WithDocs(url string) errific {
return e.New().WithDocs(url)
}
func (e Err) WithTags(tags ...string) errific {
return e.New().WithTags(tags...)
}
func (e Err) WithLabel(key, value string) errific {
return e.New().WithLabel(key, value)
}
func (e Err) WithLabels(labels map[string]string) errific {
return e.New().WithLabels(labels)
}
func (e Err) WithTimestamp(t time.Time) errific {
return e.New().WithTimestamp(t)
}
func (e Err) WithDuration(d time.Duration) errific {
return e.New().WithDuration(d)
}
// Context is a map of key-value pairs that provides additional context for errors.
// This structured data can be used for debugging, logging, and automated error handling.
type Context map[string]any
// Category represents the category of an error for automated handling.
type Category string
const (
// CategoryClient represents client-side errors (4xx).
CategoryClient Category = "client"
// CategoryServer represents server-side errors (5xx).
CategoryServer Category = "server"
// CategoryNetwork represents network connectivity errors.
CategoryNetwork Category = "network"
// CategoryValidation represents input validation errors.
CategoryValidation Category = "validation"
// CategoryNotFound represents resource not found errors (404).
CategoryNotFound Category = "not_found"
// CategoryUnauthorized represents authentication/authorization errors (401/403).
CategoryUnauthorized Category = "unauthorized"
// CategoryTimeout represents timeout errors.
CategoryTimeout Category = "timeout"
)
// MCP error codes following JSON-RPC 2.0 specification.
// These codes enable errific errors to be serialized in MCP-compatible format
// for AI tool calling and Model Context Protocol integration.
//
// Valid code ranges per JSON-RPC 2.0 specification:
// - Standard errors: -32768 to -32000 (reserved by JSON-RPC 2.0)
// - Server errors: -32000 to -32099 (available for application-specific errors)
//
// When using WithMCPCode(), use the predefined constants below or custom codes
// in the -32000 to -32099 range for application-specific errors.
//
// References:
// - JSON-RPC 2.0: https://www.jsonrpc.org/specification
// - Model Context Protocol: https://modelcontextprotocol.io
const (
// MCPParseError represents invalid JSON was received by the server.
MCPParseError = -32700
// MCPInvalidRequest represents the JSON sent is not a valid Request object.
MCPInvalidRequest = -32600
// MCPMethodNotFound represents the method does not exist / is not available.
MCPMethodNotFound = -32601
// MCPInvalidParams represents invalid method parameter(s).
MCPInvalidParams = -32602
// MCPInternalError represents internal JSON-RPC error.
MCPInternalError = -32603
// MCPToolError represents a tool execution error (custom range -32000 to -32099).
MCPToolError = -32000
)
// MCPError represents a Model Context Protocol error in JSON-RPC 2.0 format.
// This format is compatible with MCP server error responses and AI tool calling protocols.
type MCPError struct {
Code int `json:"code"`
Message string `json:"message"`
Data json.RawMessage `json:"data,omitempty"`
}
// Error implements the error interface for MCPError.
func (m MCPError) Error() string {
return fmt.Sprintf("MCP error %d: %s", m.Code, m.Message)
}
// configSnapshot captures configuration at error creation time.
// This prevents race conditions and ensures consistent formatting.
type configSnapshot struct {
caller callerOption
layout layoutOption
withStack bool
outputFormat outputFormatOption
verbosity verbosityOption
showCode bool
showCategory bool
showContext bool
showHTTPStatus bool
showRetryMeta bool
showMCPData bool
showTags bool
showLabels bool
showTimestamps bool
}
type errific struct {
err error // primary error.
errs []error // errors used in string output, and satisfy errors.Is.
unwrap []error // errors not used in string output, but satisfy errors.Is.
caller string // caller information.
stack []byte // optional stack buffer.
context Context // structured context data.
code string // error code for machine-readable identification.
category Category // error category for automated handling.
retryable bool // whether this error is retryable.
retryAfter time.Duration // suggested retry delay.
maxRetries int // maximum number of retry attempts.
httpStatus int // HTTP status code (0 if not applicable).
mcpCode int // MCP error code for JSON-RPC 2.0 compatibility (0 if not applicable).
// Phase 2A: MCP & RAG features
correlationID string // correlation ID for distributed tracing.
requestID string // request ID for this operation.
userID string // user ID associated with the error.
sessionID string // session ID for multi-step operations.
help string // help text for recovery.
suggestion string // suggested action to resolve error.
docsURL string // documentation URL for more info.
tags []string // semantic tags for RAG search and categorization.
labels map[string]string // key-value labels for filtering and grouping.
timestamp time.Time // when the error occurred.
duration time.Duration // operation duration before error.
// Configuration snapshot at error creation time
cfg configSnapshot
}
func (e errific) Error() string {
// Use configuration snapshot from error creation time
// This prevents race conditions and ensures consistent formatting
switch e.cfg.outputFormat {
case OutputJSON:
return e.formatJSON()
case OutputJSONPretty:
return e.formatJSONPretty()
case OutputCompact:
return e.formatCompact()
default: // OutputPretty
return e.formatPretty()
}
}
// formatPretty formats the error as human-readable multi-line text.
func (e errific) formatPretty() string {
var msg string
// Build the base message with caller
switch e.cfg.caller {
case Disabled:
msg = e.err.Error()
case Prefix:
msg = fmt.Sprintf("[%s] %s", e.caller, e.err.Error())
default: // Suffix
msg = fmt.Sprintf("%s [%s]", e.err.Error(), e.caller)
}
// Add wrapped errors
switch e.cfg.layout {
case Inline:
for i := range e.errs {
if e.errs[i] != nil {
msg = fmt.Sprintf("%s ↩ %s", msg, e.errs[i].Error())
}
}
default: // Newline
for i := range e.errs {
if e.errs[i] != nil {
msg = fmt.Sprintf("%s\n%s", msg, e.errs[i].Error())
}
}
}
// Add metadata fields based on verbosity
var fields []string
if e.cfg.showCode && e.code != "" {
fields = append(fields, fmt.Sprintf(" code: %s", e.code))
}
if e.cfg.showCategory && e.category != "" {
fields = append(fields, fmt.Sprintf(" category: %s", e.category))
}
if e.cfg.showContext && len(e.context) > 0 {
fields = append(fields, fmt.Sprintf(" context: %v", e.context))
}
if e.cfg.showHTTPStatus && e.httpStatus != 0 {
fields = append(fields, fmt.Sprintf(" http_status: %d", e.httpStatus))
}
if e.cfg.showRetryMeta {
if e.retryable {
fields = append(fields, " retryable: true")
}
if e.retryAfter > 0 {
fields = append(fields, fmt.Sprintf(" retry_after: %s", e.retryAfter))
}
if e.maxRetries > 0 {
fields = append(fields, fmt.Sprintf(" max_retries: %d", e.maxRetries))
}
}
if e.cfg.showMCPData {
if e.mcpCode != 0 {
fields = append(fields, fmt.Sprintf(" mcp_code: %d", e.mcpCode))
}
if e.correlationID != "" {
fields = append(fields, fmt.Sprintf(" correlation_id: %s", e.correlationID))
}
if e.requestID != "" {
fields = append(fields, fmt.Sprintf(" request_id: %s", e.requestID))
}
if e.userID != "" {
fields = append(fields, fmt.Sprintf(" user_id: %s", e.userID))
}
if e.sessionID != "" {
fields = append(fields, fmt.Sprintf(" session_id: %s", e.sessionID))
}
if e.help != "" {
fields = append(fields, fmt.Sprintf(" help: %s", e.help))
}
if e.suggestion != "" {
fields = append(fields, fmt.Sprintf(" suggestion: %s", e.suggestion))
}
if e.docsURL != "" {
fields = append(fields, fmt.Sprintf(" docs: %s", e.docsURL))
}
}
if e.cfg.showTags && len(e.tags) > 0 {
fields = append(fields, fmt.Sprintf(" tags: %v", e.tags))
}
if e.cfg.showLabels && len(e.labels) > 0 {
fields = append(fields, fmt.Sprintf(" labels: %v", e.labels))
}
if e.cfg.showTimestamps {
if !e.timestamp.IsZero() {
fields = append(fields, fmt.Sprintf(" timestamp: %s", e.timestamp.Format(time.RFC3339)))
}
if e.duration > 0 {
fields = append(fields, fmt.Sprintf(" duration: %s", e.duration))
}
}
// Append all fields
if len(fields) > 0 {
msg += "\n" + strings.Join(fields, "\n")
}
// Add stack trace if configured
if e.cfg.withStack && len(e.stack) > 0 {
msg += string(e.stack)
}
return msg
}
// formatJSON formats the error as compact JSON.
func (e errific) formatJSON() string {
data, err := json.Marshal(e)
if err != nil {
// Fallback to simple error message if marshaling fails
return fmt.Sprintf(`{"error":"%s"}`, e.err.Error())
}
return string(data)
}
// formatJSONPretty formats the error as indented JSON.
func (e errific) formatJSONPretty() string {
data, err := json.MarshalIndent(e, "", " ")
if err != nil {
// Fallback to simple error message if marshaling fails
return fmt.Sprintf(`{\n "error": "%s"\n}`, e.err.Error())
}
return string(data)
}
// formatCompact formats the error as single-line text with key=value pairs.
func (e errific) formatCompact() string {
var parts []string
// Base message with caller
switch e.cfg.caller {
case Disabled:
parts = append(parts, e.err.Error())
case Prefix:
parts = append(parts, fmt.Sprintf("[%s] %s", e.caller, e.err.Error()))
default: // Suffix
parts = append(parts, fmt.Sprintf("%s [%s]", e.err.Error(), e.caller))
}
// Add wrapped errors inline
for i := range e.errs {
if e.errs[i] != nil {
parts = append(parts, "↩", e.errs[i].Error())
}
}
// Add metadata as key=value pairs
if e.cfg.showCode && e.code != "" {
parts = append(parts, fmt.Sprintf("code=%s", e.code))
}
if e.cfg.showCategory && e.category != "" {
parts = append(parts, fmt.Sprintf("category=%s", e.category))
}
if e.cfg.showContext && len(e.context) > 0 {
for k, v := range e.context {
parts = append(parts, fmt.Sprintf("%s=%v", k, v))
}
}
if e.cfg.showHTTPStatus && e.httpStatus != 0 {
parts = append(parts, fmt.Sprintf("http_status=%d", e.httpStatus))
}
if e.cfg.showRetryMeta {
if e.retryable {
parts = append(parts, "retryable=true")
}
if e.retryAfter > 0 {
parts = append(parts, fmt.Sprintf("retry_after=%s", e.retryAfter))
}
if e.maxRetries > 0 {
parts = append(parts, fmt.Sprintf("max_retries=%d", e.maxRetries))
}
}
if e.cfg.showMCPData {
if e.correlationID != "" {
parts = append(parts, fmt.Sprintf("correlation_id=%s", e.correlationID))
}
if e.requestID != "" {
parts = append(parts, fmt.Sprintf("request_id=%s", e.requestID))
}
}
if e.cfg.showTags && len(e.tags) > 0 {
parts = append(parts, fmt.Sprintf("tags=%v", e.tags))
}
if e.cfg.showLabels && len(e.labels) > 0 {
for k, v := range e.labels {
parts = append(parts, fmt.Sprintf("label_%s=%s", k, v))
}
}
return strings.Join(parts, " ")
}
func (e errific) Join(errs ...error) error {
e.errs = append(e.errs, errs...)
return e
}
func (e errific) Withf(format string, a ...any) errific {
originalErr := e.err
format = e.err.Error() + ": " + format
e.err = fmt.Errorf(format, a...)
e.unwrap = append(e.unwrap, originalErr)
return e
}
func (e errific) Wrapf(format string, a ...any) errific {
e.errs = append(e.errs, fmt.Errorf(format, a...))
return e
}
// WithContext adds structured context data to the error.
// Context is a map of key-value pairs that can be used for debugging,
// logging, and automated error handling.
//
// err := ErrDatabaseQuery.New(sqlErr).WithContext(errific.Context{
// "query": "SELECT * FROM users",
// "duration_ms": 1500,
// })
func (e errific) WithContext(ctx Context) errific {
if e.context == nil {
e.context = make(Context)
}
for k, v := range ctx {
e.context[k] = v
}
return e
}
// WithCode sets an error code for machine-readable identification.
// Error codes enable automated error handling and routing.
//
// Empty strings are ignored (code remains unset).
//
// err := ErrDatabaseConnection.New().WithCode("DB_CONN_TIMEOUT")
func (e errific) WithCode(code string) errific {
// Ignore empty codes
if code != "" {
e.code = code
}
return e
}
// WithCategory sets the error category for automated handling.
// Categories help AI agents and automation systems decide how to respond.
//
// err := ErrDatabaseConnection.New().WithCategory(errific.CategoryNetwork)
func (e errific) WithCategory(category Category) errific {
e.category = category
return e
}
// WithRetryable marks whether the error is retryable.
// This enables automated retry logic in AI agents and resilience systems.
//
// err := ErrAPICall.New(httpErr).WithRetryable(true)
func (e errific) WithRetryable(retryable bool) errific {
e.retryable = retryable
return e
}
// WithRetryAfter sets the suggested retry delay duration.
// This guides automated retry strategies with appropriate backoff.
//
// Negative durations are treated as 0 (no delay).
//
// err := ErrRateLimit.New().WithRetryAfter(5 * time.Second)
func (e errific) WithRetryAfter(duration time.Duration) errific {
// Ensure non-negative duration
if duration < 0 {
duration = 0
}
e.retryAfter = duration
return e
}
// WithMaxRetries sets the maximum number of retry attempts.
// This prevents infinite retry loops in automated systems.
//
// Negative values are treated as 0 (no retries).
//
// err := ErrAPICall.New().WithRetryable(true).WithMaxRetries(3)
func (e errific) WithMaxRetries(max int) errific {
// Ensure non-negative retry count
if max < 0 {
max = 0
}
e.maxRetries = max
return e
}
// WithHTTPStatus sets the HTTP status code for this error.
// This enables automatic HTTP response handling in web services.
//
// Valid HTTP status codes are in the range 100-599.
// Panics if status is outside this range and non-zero.
//
// err := ErrValidation.New().WithHTTPStatus(400)
func (e errific) WithHTTPStatus(status int) errific {
// Validate HTTP status code range
// Allow 0 (unset) or valid HTTP status codes (100-599)
if status != 0 && (status < 100 || status > 599) {
panic(fmt.Sprintf("invalid HTTP status code %d: must be 0 or in range 100-599", status))
}
e.httpStatus = status
return e
}
// WithMCPCode sets an MCP error code following JSON-RPC 2.0 specification.
// Use the predefined MCP constants (MCPInternalError, MCPInvalidParams, etc.)
// or custom codes in the range -32000 to -32099 for application-specific errors.
//
// Valid code ranges per JSON-RPC 2.0:
// - Standard errors: -32768 to -32000
// - Zero (0) is treated as unset/default
//
// Panics if code is outside valid range and non-zero.
//
// err := ErrToolExecution.New().WithMCPCode(MCPToolError)
func (e errific) WithMCPCode(code int) errific {
// Validate JSON-RPC 2.0 code ranges
// Allow 0 (unset), and -32768 to -32000 (reserved range)
if code != 0 && (code > -32000 || code < -32768) {
panic(fmt.Sprintf("invalid MCP code %d: must be 0 or in range -32768 to -32000 per JSON-RPC 2.0 specification", code))
}
e.mcpCode = code
return e
}
// WithCorrelationID sets a correlation ID for distributed tracing.
// This enables tracking errors across MCP tool calls and distributed systems.
//
// Empty strings are ignored (ID remains unset).
//
// err := ErrMCPTool.New().WithCorrelationID(correlationID)
func (e errific) WithCorrelationID(id string) errific {
if id != "" {
e.correlationID = id
}
return e
}
// WithRequestID sets a request ID for this specific operation.
// This enables tracking individual requests in logging and monitoring.
//
// Empty strings are ignored (ID remains unset).
//
// err := ErrAPI.New().WithRequestID(uuid.New().String())
func (e errific) WithRequestID(id string) errific {
if id != "" {
e.requestID = id
}
return e
}
// WithUserID sets the user ID associated with this error.
// This enables user-specific error tracking and analysis.
//
// Empty strings are ignored (ID remains unset).
//
// err := ErrPermission.New().WithUserID(userID)
func (e errific) WithUserID(id string) errific {
if id != "" {
e.userID = id
}
return e
}
// WithSessionID sets a session ID for multi-step operations.
// This enables tracking errors across agent conversation sessions.
//
// Empty strings are ignored (ID remains unset).
//
// err := ErrAgent.New().WithSessionID(sessionID)
func (e errific) WithSessionID(id string) errific {
if id != "" {
e.sessionID = id
}
return e
}
// WithHelp adds recovery help text to the error.
// This enables AI agents to display actionable guidance to users.
//
// Empty strings are ignored (help remains unset).
//
// err := ErrPermission.New().WithHelp("Run 'kubectl get roles' to check permissions")
func (e errific) WithHelp(text string) errific {
if text != "" {
e.help = text
}
return e
}
// WithSuggestion adds a suggested action to resolve the error.
// This enables AI agents to attempt automatic recovery.
//
// Empty strings are ignored (suggestion remains unset).
//
// err := ErrRateLimit.New().WithSuggestion("Reduce request frequency or upgrade plan")
func (e errific) WithSuggestion(text string) errific {
if text != "" {
e.suggestion = text
}
return e
}
// WithDocs adds a documentation URL for more information.
// This enables AI agents to provide users with detailed documentation.
//
// Empty strings are ignored (URL remains unset).
//
// err := ErrConfig.New().WithDocs("https://docs.example.com/configuration")
func (e errific) WithDocs(url string) errific {
if url != "" {
e.docsURL = url
}
return e
}
// WithTags adds semantic tags for RAG search and categorization.
// Tags enable semantic search, error clustering, and pattern recognition.
//
// err := ErrMCPTool.New().WithTags("mcp", "tool", "search", "timeout")
func (e errific) WithTags(tags ...string) errific {
e.tags = append(e.tags, tags...)
return e
}
// WithLabels adds key-value labels for filtering and grouping.
// Labels enable precise error filtering in monitoring and analytics.
//
// err := ErrAPI.New().WithLabels(map[string]string{
// "environment": "production",
// "region": "us-east-1",
// })
func (e errific) WithLabels(labels map[string]string) errific {
if e.labels == nil {
e.labels = make(map[string]string)
}
for k, v := range labels {
e.labels[k] = v
}
return e
}
// WithLabel adds a single key-value label.
// Convenience method for adding individual labels.
//
// err := ErrAPI.New().WithLabel("environment", "production")
func (e errific) WithLabel(key, value string) errific {
if e.labels == nil {
e.labels = make(map[string]string)
}
e.labels[key] = value
return e
}
// WithTimestamp sets when the error occurred.
// If not set, defaults to time of error creation.
//
// err := ErrOperation.New().WithTimestamp(time.Now())
func (e errific) WithTimestamp(t time.Time) errific {
e.timestamp = t
return e
}
// WithDuration sets the operation duration before the error occurred.
// This enables performance analysis and SLA monitoring.
//
// err := ErrSlowQuery.New().WithDuration(elapsed)
func (e errific) WithDuration(d time.Duration) errific {
e.duration = d
return e
}
func (e errific) Unwrap() []error {
// Deduplicate errors to prevent same error appearing multiple times
// in the error chain (can happen with complex wrapping scenarios)
var errs []error
add := func(err error) {
if err == nil {
return
}
// Check if already added (linear search is fine for small error lists)
for _, existing := range errs {
if existing == err {
return
}
}
errs = append(errs, err)
}
add(e.err)
for _, err := range e.errs {
add(err)
}
for _, err := range e.unwrap {
add(err)
}
return errs
}
// MarshalJSON implements json.Marshaler for structured error output.
// This enables errific errors to be serialized to JSON for logging,
// API responses, and integration with monitoring systems.
func (e errific) MarshalJSON() ([]byte, error) {
type jsonError struct {
Error string `json:"error"`
Code string `json:"code,omitempty"`
Category Category `json:"category,omitempty"`
Caller string `json:"caller,omitempty"`
Context Context `json:"context,omitempty"`
Retryable bool `json:"retryable,omitempty"`
RetryAfter string `json:"retry_after,omitempty"`
MaxRetries int `json:"max_retries,omitempty"`
HTTPStatus int `json:"http_status,omitempty"`
MCPCode int `json:"mcp_code,omitempty"`
Stack []string `json:"stack,omitempty"`
Wrapped []string `json:"wrapped,omitempty"`
CorrelationID string `json:"correlation_id,omitempty"`
RequestID string `json:"request_id,omitempty"`
UserID string `json:"user_id,omitempty"`
SessionID string `json:"session_id,omitempty"`
Help string `json:"help,omitempty"`
Suggestion string `json:"suggestion,omitempty"`
Docs string `json:"docs,omitempty"`
Tags []string `json:"tags,omitempty"`
Labels map[string]string `json:"labels,omitempty"`
Timestamp string `json:"timestamp,omitempty"`
Duration string `json:"duration,omitempty"`
}
je := jsonError{
Error: e.err.Error(),
Code: e.code,
Category: e.category,
Caller: e.caller,
Context: e.context,
Retryable: e.retryable,
MaxRetries: e.maxRetries,
HTTPStatus: e.httpStatus,
MCPCode: e.mcpCode,
CorrelationID: e.correlationID,
RequestID: e.requestID,
UserID: e.userID,
SessionID: e.sessionID,
Help: e.help,
Suggestion: e.suggestion,
Docs: e.docsURL,
Tags: e.tags,
Labels: e.labels,
}
if e.retryAfter > 0 {
je.RetryAfter = e.retryAfter.String()
}
if !e.timestamp.IsZero() {
je.Timestamp = e.timestamp.Format(time.RFC3339)
}
if e.duration > 0 {
je.Duration = e.duration.String()
}
// Parse stack trace into lines
if len(e.stack) > 0 {
stackLines := strings.Split(strings.TrimSpace(string(e.stack)), "\n")
je.Stack = stackLines
}
// Add wrapped errors
for _, err := range e.errs {
je.Wrapped = append(je.Wrapped, err.Error())
}
return json.Marshal(je)
}
func unwrapStack(errs []any) []byte {
for _, err := range errs {
if err == nil {
return nil
}
if e, ok := err.(errific); ok {
return e.stack
}
if err, ok := err.(error); ok {
return unwrapStack([]any{errors.Unwrap(err)})
}
}
return nil
}
// captureConfig captures the current configuration as a snapshot.
// This must be called with cMu held (either RLock or Lock).
func captureConfig() configSnapshot {
return configSnapshot{
caller: c.caller,
layout: c.layout,
withStack: bool(c.withStack),
outputFormat: c.outputFormat,
verbosity: c.verbosity,
showCode: c.showCode,
showCategory: c.showCategory,
showContext: c.showContext,
showHTTPStatus: c.showHTTPStatus,
showRetryMeta: c.showRetryMetadata,
showMCPData: c.showMCPData,
showTags: c.showTags,
showLabels: c.showLabels,
showTimestamps: c.showTimestamps,
}
}
func callstack(errs []any) (caller string, stack []byte, cfg configSnapshot) {
pc := make([]uintptr, 32)
n := runtime.Callers(3, pc)
if n == 0 {
// Capture config snapshot even if no caller info
cMu.RLock()
cfg = captureConfig()
cMu.RUnlock()
return "", stack, cfg
}
frames := runtime.CallersFrames(pc)
frame, more := frames.Next()
caller = parseFrame(frame)
// Capture configuration snapshot once at error creation time
cMu.RLock()
cfg = captureConfig()
cMu.RUnlock()
if !cfg.withStack {