File: README.md

package info (click to toggle)
golang-github-olekukonko-errors 1.1.0-2
  • links: PTS, VCS
  • area: main
  • in suites: experimental, forky, sid
  • size: 500 kB
  • sloc: makefile: 2
file content (1565 lines) | stat: -rw-r--r-- 36,338 bytes parent folder | download | duplicates (2)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
# Enhanced Error Handling for Go with Context, Stack Traces, Monitoring, and More

[![Go Reference](https://pkg.go.dev/badge/github.com/olekukonko/errors.svg)](https://pkg.go.dev/github.com/olekukonko/errors)
[![Go Report Card](https://goreportcard.com/badge/github.com/olekukonko/errors)](https://goreportcard.com/report/github.com/olekukonko/errors)
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
[![Benchmarks](https://img.shields.io/badge/benchmarks-included-success)](README.md#benchmarks)

A production-grade error handling library for Go, offering zero-cost abstractions, stack traces, multi-error support, retries, and advanced monitoring through two complementary packages: `errors` (core) and `errmgr` (management).

## Features

### `errors` Package (Core)
- **Performance Optimized**
  - Optional memory pooling (12 ns/op with pooling)
  - Lazy stack trace collection (205 ns/op with stack)
  - Small context optimization (≤4 items, 40 ns/op)
  - Lock-free configuration reads

- **Debugging Tools**
  - Full stack traces with internal frame filtering
  - Error wrapping and chaining
  - Structured context attachment
  - JSON serialization (662 ns/op)

- **Advanced Utilities**
  - Configurable retry mechanism
  - Multi-error aggregation with sampling
  - HTTP status code support
  - Callback triggers for cleanup or side effects

### `errmgr` Package (Management)
- **Production Monitoring**
  - Error occurrence counting
  - Threshold-based alerting
  - Categorized metrics
  - Predefined error templates

## Installation

```bash
go get github.com/olekukonko/errors@latest
```

## Package Overview

- **`errors`**: Core error handling with creation, wrapping, context, stack traces, retries, and multi-error support.
- **`errmgr`**: Error management with templates, monitoring, and predefined errors for consistent application use.

---

> [!NOTE]  
> ✓ added support for `errors.Errorf("user %w not found", errors.New("bob"))`  
> ✓ added support for `sequential chain` execution
``

## Using the `errors` Package

### Basic Error Creation

#### Simple Error
```go
package main

import (
  "fmt"
  "github.com/olekukonko/errors"
)

func main() {
  // Fast error with no stack trace
  err := errors.New("connection failed")
  fmt.Println(err) // "connection failed"

  // Standard error, no allocation, same speed
  stdErr := errors.Std("connection failed")
  fmt.Println(stdErr) // "connection failed"
}
```

#### Formatted Error
```go
// main.go
package main

import (
  "fmt"
  "github.com/olekukonko/errors"
)

func main() {
  // Formatted error without stack trace
  errNoWrap := errors.Newf("user %s not found", "bob")
  fmt.Println(errNoWrap) // Output: "user bob not found"

  // Standard formatted error, no fmt.Errorf needed (using own pkg)
  stdErrNoWrap := errors.Stdf("user %s not found", "bob")
  fmt.Println(stdErrNoWrap) // Output: "user bob not found"

  // Added support for %w (compatible with fmt.Errorf output)
  // errors.Errorf is alias of errors.Newf
  errWrap := errors.Errorf("user %w not found", errors.New("bob"))
  fmt.Println(errWrap) // Output: "user bob not found"

  // Standard formatted error for comparison
  stdErrWrap := fmt.Errorf("user %w not found", fmt.Errorf("bob"))
  fmt.Println(stdErrWrap) // Output: "user bob not found"
}
```

#### Error with Stack Trace
```go
package main

import (
  "fmt"
  "github.com/olekukonko/errors"
)

func main() {
  // Create an error with stack trace using Trace
  err := errors.Trace("critical issue")
  fmt.Println(err)         // Output: "critical issue"
  fmt.Println(err.Stack()) // Output: e.g., ["main.go:15", "caller.go:42"]

  // Convert basic error to traceable with WithStack
  errS := errors.New("critical issue")
  errS = errS.WithStack()   // Add stack trace and update error
  fmt.Println(errS)         // Output: "critical issue"
  fmt.Println(errS.Stack()) // Output: e.g., ["main.go:19", "caller.go:42"]
}
```

#### Named Error
```go
package main

import (
	"fmt"
	"github.com/olekukonko/errors"
)

func main() {
	// Create a named error with stack trace
	err := errors.Named("InputError")
	fmt.Println(err.Name()) // Output: "InputError"
	fmt.Println(err)        // Output: "InputError"
}
```

### Adding Context

#### Basic Context
```go
package main

import (
	"fmt"
	"github.com/olekukonko/errors"
)

func main() {
	// Create an error with context
	err := errors.New("processing failed").
		With("id", "123").
		With("attempt", 3).
		With("retryable", true)
	fmt.Println("Error:", err)                    // Output: "processing failed"
	fmt.Println("Full context:", errors.Context(err)) // Output: map[id:123 attempt:3 retryable:true]
}
```

#### Context with Wrapped Standard Error
```go
package main

import (
	"fmt"
	"github.com/olekukonko/errors"
)

func main() {
	// Wrap a standard error and add context
	err := errors.New("processing failed").
		With("id", "123")
	wrapped := fmt.Errorf("wrapped: %w", err)
	fmt.Println("Wrapped error:", wrapped)             // Output: "wrapped: processing failed"
	fmt.Println("Direct context:", errors.Context(wrapped)) // Output: nil

	// Convert to access context
	e := errors.Convert(wrapped)
	fmt.Println("Converted context:", e.Context()) // Output: map[id:123]
}
```

#### Adding Context to Standard Error
```go
package main

import (
	"fmt"
	"github.com/olekukonko/errors"
)

func main() {
	// Convert a standard error and add context
	stdErr := fmt.Errorf("standard error")
	converted := errors.Convert(stdErr).
		With("source", "legacy").
		With("severity", "high")
	fmt.Println("Message:", converted.Error()) // Output: "standard error"
	fmt.Println("Context:", converted.Context()) // Output: map[source:legacy severity:high]
}
```

#### Complex Context
```go
package main

import (
	"fmt"
	"github.com/olekukonko/errors"
)

func main() {
	// Create an error with complex context
	err := errors.New("database operation failed").
		With("query", "SELECT * FROM users").
		With("params", map[string]interface{}{
			"limit":  100,
			"offset": 0,
		}).
		With("duration_ms", 45.2)
	fmt.Println("Complex error context:")
	for k, v := range errors.Context(err) {
		fmt.Printf("%s: %v (%T)\n", k, v, v)
	}
	// Output:
	// query: SELECT * FROM users (string)
	// params: map[limit:100 offset:0] (map[string]interface {})
	// duration_ms: 45.2 (float64)
}
```

### Stack Traces

#### Adding Stack to Any Error
```go
package main

import (
	"fmt"
	"github.com/olekukonko/errors"
)

func main() {
	// Add stack trace to a standard error
	err := fmt.Errorf("basic error")
	enhanced := errors.WithStack(err)
	fmt.Println("Error with stack:")
	fmt.Println("Message:", enhanced.Error()) // Output: "basic error"
	fmt.Println("Stack:", enhanced.Stack())   // Output: e.g., "main.go:15"
}
```

#### Chaining with Stack
```go
package main

import (
	"fmt"
	"github.com/olekukonko/errors"
	"time"
)

func main() {
	// Create an enhanced error and add stack/context
	err := errors.New("validation error").
		With("field", "email")
	stackErr := errors.WithStack(err).
		With("timestamp", time.Now()).
		WithCode(500)
	fmt.Println("Message:", stackErr.Error()) // Output: "validation error"
	fmt.Println("Context:", stackErr.Context()) // Output: map[field:email timestamp:...]
	fmt.Println("Stack:")
	for _, frame := range stackErr.Stack() {
		fmt.Println(frame)
	}
}
```
### Stack Traces with `WithStack()`
```go
package main

import (
	"fmt"
	"github.com/olekukonko/errors"
	"math/rand"
	"time"
)

func basicFunc() error {
	return fmt.Errorf("basic error")
}

func enhancedFunc() *errors.Error {
	return errors.New("enhanced error")
}

func main() {
	// 1. Package-level WithStack - works with ANY error type
	err1 := basicFunc()
	enhanced1 := errors.WithStack(err1) // Handles basic errors
	fmt.Println("Package-level WithStack:")
	fmt.Println(enhanced1.Stack())

	// 2. Method-style WithStack - only for *errors.Error
	err2 := enhancedFunc()
	enhanced2 := err2.WithStack() // More natural chaining
	fmt.Println("\nMethod-style WithStack:")
	fmt.Println(enhanced2.Stack())

	// 3. Combined usage in real-world scenario
	result := processData()
	if result != nil {
		// Use package-level when type is unknown
		stackErr := errors.WithStack(result)

		// Then use method-style for chaining
		finalErr := stackErr.
			With("timestamp", time.Now()).
			WithCode(500)

		fmt.Println("\nCombined Usage:")
		fmt.Println("Message:", finalErr.Error())
		fmt.Println("Context:", finalErr.Context())
		fmt.Println("Stack:")
		for _, frame := range finalErr.Stack() {
			fmt.Println(frame)
		}
	}
}

func processData() error {
	// Could return either basic or enhanced error
	if rand.Intn(2) == 0 {
		return fmt.Errorf("database error")
	}
	return errors.New("validation error").With("field", "email")
}
```

### Error Wrapping and Chaining

#### Basic Wrapping
```go
package main

import (
	"fmt"
	"github.com/olekukonko/errors"
)

func main() {
	// Wrap an error with additional context
	lowErr := errors.New("low-level failure")
	highErr := errors.Wrapf(lowErr, "high-level operation failed: %s", "details")
	fmt.Println(highErr)           // Output: "high-level operation failed: details: low-level failure"
	fmt.Println(errors.Unwrap(highErr)) // Output: "low-level failure"
}
```

#### Walking Error Chain
```go
package main

import (
	"fmt"
	"github.com/olekukonko/errors"
)

func main() {
	// Create a chained error
	dbErr := errors.New("connection timeout").
		With("server", "db01.prod")
	bizErr := errors.New("failed to process user 12345").
		With("user_id", "12345").
		Wrap(dbErr)
	apiErr := errors.New("API request failed").
		WithCode(500).
		Wrap(bizErr)

	// Walk the error chain
	fmt.Println("Error Chain:")
	for i, e := range errors.UnwrapAll(apiErr) {
		fmt.Printf("%d. %s\n", i+1, e)
	}
	// Output:
	// 1. API request failed
	// 2. failed to process user 12345
	// 3. connection timeout
}
```

### Type Assertions

#### Using Is
```go
package main

import (
	"fmt"
	"github.com/olekukonko/errors"
)

func main() {
	// Check error type with Is
	err := errors.Named("AuthError")
	wrapped := errors.Wrapf(err, "login failed")
	if errors.Is(wrapped, err) {
		fmt.Println("Is an AuthError") // Output: "Is an AuthError"
	}
}
```

#### Using As
```go
package main

import (
	"fmt"
	"github.com/olekukonko/errors"
)

func main() {
	// Extract error type with As
	err := errors.Named("AuthError")
	wrapped := errors.Wrapf(err, "login failed")
	var authErr *errors.Error
	if wrapped.As(&authErr) {
		fmt.Println("Extracted:", authErr.Name()) // Output: "Extracted: AuthError"
	}
}
```

### Retry Mechanism

#### Basic Retry
```go
package main

import (
  "fmt"
  "github.com/olekukonko/errors"
  "math/rand"
  "time"
)

func main() {
  // Simulate a flaky operation
  attempts := 0
  retry := errors.NewRetry(
    errors.WithMaxAttempts(3),
    errors.WithDelay(100*time.Millisecond),
  )
  err := retry.Execute(func() error {
    attempts++
    if rand.Intn(2) == 0 {
      return errors.New("temporary failure").WithRetryable()
    }
    return nil
  })
  if err != nil {
    fmt.Printf("Failed after %d attempts: %v\n", attempts, err)
  } else {
    fmt.Printf("Succeeded after %d attempts\n", attempts)
  }
}

```

#### Retry with Context Timeout
```go
package main

import (
	"context"
	"fmt"
	"github.com/olekukonko/errors"
	"time"
)

func main() {
	// Retry with context timeout
	ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
	defer cancel()
	retry := errors.NewRetry(
		errors.WithContext(ctx),
		errors.WithMaxAttempts(5),
		errors.WithDelay(200*time.Millisecond),
	)
	err := retry.Execute(func() error {
		return errors.New("operation failed").WithRetryable()
	})
	if errors.Is(err, context.DeadlineExceeded) {
		fmt.Println("Operation timed out:", err)
	} else if err != nil {
		fmt.Println("Operation failed:", err)
	}
}
```


### Retry Comprehensive

```go
package main

import (
  "context"
  "fmt"
  "github.com/olekukonko/errors"
  "math/rand"
  "time"
)

// DatabaseClient simulates a flaky database connection
type DatabaseClient struct {
  healthyAfterAttempt int
}

func (db *DatabaseClient) Query() error {
  if db.healthyAfterAttempt > 0 {
    db.healthyAfterAttempt--
    return errors.New("database connection failed").
      With("attempt_remaining", db.healthyAfterAttempt).
      WithRetryable() // Mark as retryable
  }
  return nil
}

// ExternalService simulates an unreliable external API
func ExternalService() error {
  if rand.Intn(100) < 30 { // 30% failure rate
    return errors.New("service unavailable").
      WithCode(503).
      WithRetryable()
  }
  return nil
}

func main() {
  // Configure retry with exponential backoff and jitter
  retry := errors.NewRetry(
    errors.WithMaxAttempts(5),
    errors.WithDelay(200*time.Millisecond),
    errors.WithMaxDelay(2*time.Second),
    errors.WithJitter(true),
    errors.WithBackoff(errors.ExponentialBackoff{}),
    errors.WithOnRetry(func(attempt int, err error) {
      // Calculate delay using the same logic as in Execute
      baseDelay := 200 * time.Millisecond
      maxDelay := 2 * time.Second
      delay := errors.ExponentialBackoff{}.Backoff(attempt, baseDelay)
      if delay > maxDelay {
        delay = maxDelay
      }
      fmt.Printf("Attempt %d failed: %v (retrying in %v)\n",
        attempt,
        err.Error(),
        delay)
    }),
  )

  // Scenario 1: Database connection with known recovery point
  db := &DatabaseClient{healthyAfterAttempt: 3}
  fmt.Println("Starting database operation...")
  err := retry.Execute(func() error {
    return db.Query()
  })
  if err != nil {
    fmt.Printf("Database operation failed after %d attempts: %v\n", retry.Attempts(), err)
  } else {
    fmt.Println("Database operation succeeded!")
  }

  // Scenario 2: External service with random failures
  fmt.Println("\nStarting external service call...")
  var lastAttempts int
  start := time.Now()

  // Using ExecuteReply to demonstrate return values
  result, err := errors.ExecuteReply[string](retry, func() (string, error) {
    lastAttempts++
    if err := ExternalService(); err != nil {
      return "", err
    }
    return "service response data", nil
  })

  duration := time.Since(start)

  if err != nil {
    fmt.Printf("Service call failed after %d attempts (%.2f sec): %v\n",
      lastAttempts,
      duration.Seconds(),
      err)
  } else {
    fmt.Printf("Service call succeeded after %d attempts (%.2f sec): %s\n",
      lastAttempts,
      duration.Seconds(),
      result)
  }

  // Scenario 3: Context cancellation with more visibility
  fmt.Println("\nStarting operation with timeout...")
  ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
  defer cancel()

  timeoutRetry := retry.Transform(
    errors.WithContext(ctx),
    errors.WithMaxAttempts(10),
    errors.WithOnRetry(func(attempt int, err error) {
      fmt.Printf("Timeout scenario attempt %d: %v\n", attempt, err)
    }),
  )

  startTimeout := time.Now()
  err = timeoutRetry.Execute(func() error {
    time.Sleep(300 * time.Millisecond) // Simulate long operation
    return errors.New("operation timed out")
  })

  if errors.Is(err, context.DeadlineExceeded) {
    fmt.Printf("Operation cancelled by timeout after %.2f sec: %v\n",
      time.Since(startTimeout).Seconds(),
      err)
  } else if err != nil {
    fmt.Printf("Operation failed: %v\n", err)
  } else {
    fmt.Println("Operation succeeded (unexpected)")
  }
}
```

### Multi-Error Aggregation

#### Form Validation
```go
package main

import (
	"fmt"
	"github.com/olekukonko/errors"
)

func main() {
	// Validate a form with multiple errors
	multi := errors.NewMultiError()
	multi.Add(errors.New("name is required"))
	multi.Add(errors.New("email is invalid"))
	multi.Add(errors.New("password too short"))
	if multi.Has() {
		fmt.Println(multi) // Output: "errors(3): name is required; email is invalid; password too short"
		fmt.Printf("Total errors: %d\n", multi.Count())
	}
}
```

#### Sampling Multi-Errors
```go
package main

import (
  "fmt"
  "github.com/olekukonko/errors"
)

func main() {
  // Simulate many errors with sampling
  multi := errors.NewMultiError(
    errors.WithSampling(10), // 10% sampling
    errors.WithLimit(5),
  )
  for i := 0; i < 100; i++ {
    multi.Add(errors.Newf("error %d", i))
  }
  fmt.Println(multi)
  fmt.Printf("Captured %d out of 100 errors\n", multi.Count())
}
```

### Additional Examples

#### Using Callbacks
```go
package main

import (
	"fmt"
	"github.com/olekukonko/errors"
)

func main() {
	// Add a callback to an error
	err := errors.New("transaction failed").
		Callback(func() {
			fmt.Println("Reversing transaction...")
		})
	fmt.Println(err) // Output: "transaction failed" + "Reversing transaction..."
	err.Free()
}
```

#### Copying Errors
```go
package main

import (
	"fmt"
	"github.com/olekukonko/errors"
)

func main() {
	// Copy an error and modify the copy
	original := errors.New("base error").With("key", "value")
	copied := original.Copy().With("extra", "data")
	fmt.Println("Original:", original, original.Context()) // Output: "base error" map[key:value]
	fmt.Println("Copied:", copied, copied.Context())       // Output: "base error" map[key:value extra:data]
}
```

#### Transforming Errors
```go
package main

import (
	"fmt"
	"github.com/olekukonko/errors"
)

func main() {
	// Transform an error with additional context
	err := errors.New("base error")
	transformed := errors.Transform(err, func(e *errors.Error) {
		e.With("env", "prod").
			WithCode(500).
			WithStack()
	})
	fmt.Println(transformed.Error())          // Output: "base error"
	fmt.Println(transformed.Context())        // Output: map[env:prod]
	fmt.Println(transformed.Code())           // Output: 500
	fmt.Println(len(transformed.Stack()) > 0) // Output: true
	transformed.Free()
}
```

### Transformation and Enrichment

```go
package main

import (
  "fmt"
  "github.com/olekukonko/errors"
)

func process() error {
  return errors.New("base error")
}

func main() {
  err := process()
  transformedErr := errors.Transform(err, func(e *errors.Error) {
    e.With("env", "prod").
      WithCode(500).
      WithStack()
  })

  // No type assertion needed now
  fmt.Println(transformedErr.Error())          // "base error"
  fmt.Println(transformedErr.Context())        // map[env:prod]
  fmt.Println(transformedErr.Code())           // 500
  fmt.Println(len(transformedErr.Stack()) > 0) // true
  transformedErr.Free()                        // Clean up

  stdErr := process()
  convertedErr := errors.Convert(stdErr) // Convert standard error to *Error
  convertedErr.With("source", "external").
    WithCode(400).
          Callback(func() {
            fmt.Println("Converted error processed...")
          })
  fmt.Println("Converted Error:", convertedErr.Error())
  fmt.Println("Context:", convertedErr.Context())
  fmt.Println("Code:", convertedErr.Code())
  convertedErr.Free()

}

```

#### Fast Stack Trace
```go
package main

import (
	"fmt"
	"github.com/olekukonko/errors"
)

func main() {
	// Get a lightweight stack trace
	err := errors.Trace("lightweight error")
	fastStack := err.FastStack()
	fmt.Println("Fast Stack:")
	for _, frame := range fastStack {
		fmt.Println(frame) // Output: e.g., "main.go:15"
	}
}
```

#### WarmStackPool
```go
package main

import (
	"fmt"
	"github.com/olekukonko/errors"
)

func main() {
	// Pre-warm the stack pool
	errors.WarmStackPool(10)
	err := errors.Trace("pre-warmed error")
	fmt.Println("Stack after warming pool:")
	for _, frame := range err.Stack() {
		fmt.Println(frame)
	}
}
```

### Multi-Error Aggregation

```go
package main

import (
  "fmt"
  "net/mail"
  "strings"
  "time"

  "github.com/olekukonko/errors"
)

type UserForm struct {
  Name     string
  Email    string
  Password string
  Birthday string
}

func validateUser(form UserForm) *errors.MultiError {
  multi := errors.NewMultiError(
    errors.WithLimit(10),
    errors.WithFormatter(customFormat),
  )

  // Name validation
  if form.Name == "" {
    multi.Add(errors.New("name is required"))
  } else if len(form.Name) > 50 {
    multi.Add(errors.New("name cannot exceed 50 characters"))
  }

  // Email validation
  if form.Email == "" {
    multi.Add(errors.New("email is required"))
  } else {
    if _, err := mail.ParseAddress(form.Email); err != nil {
      multi.Add(errors.New("invalid email format"))
    }
    if !strings.Contains(form.Email, "@") {
      multi.Add(errors.New("email must contain @ symbol"))
    }
  }

  // Password validation
  if len(form.Password) < 8 {
    multi.Add(errors.New("password must be at least 8 characters"))
  }
  if !strings.ContainsAny(form.Password, "0123456789") {
    multi.Add(errors.New("password must contain at least one number"))
  }
  if !strings.ContainsAny(form.Password, "!@#$%^&*") {
    multi.Add(errors.New("password must contain at least one special character"))
  }

  // Birthday validation
  if form.Birthday != "" {
    if _, err := time.Parse("2006-01-02", form.Birthday); err != nil {
      multi.Add(errors.New("birthday must be in YYYY-MM-DD format"))
    } else if bday, _ := time.Parse("2006-01-02", form.Birthday); time.Since(bday).Hours()/24/365 < 13 {
      multi.Add(errors.New("must be at least 13 years old"))
    }
  }

  return multi
}

func customFormat(errs []error) string {
  var sb strings.Builder
  sb.WriteString("🚨 Validation Errors:\n")
  for i, err := range errs {
    sb.WriteString(fmt.Sprintf("  %d. %s\n", i+1, err))
  }
  sb.WriteString(fmt.Sprintf("\nTotal issues found: %d\n", len(errs)))
  return sb.String()
}

func main() {
  fmt.Println("=== User Registration Validation ===")

  user := UserForm{
    Name:     "", // Empty name
    Email:    "invalid-email",
    Password: "weak",
    Birthday: "2015-01-01", // Under 13
  }

  // Generate multiple validation errors
  validationErrors := validateUser(user)

  if validationErrors.Has() {
    fmt.Println(validationErrors)

    // Detailed error analysis
    fmt.Println("\n🔍 Error Analysis:")
    fmt.Printf("Total errors: %d\n", validationErrors.Count())
    fmt.Printf("First error: %v\n", validationErrors.First())
    fmt.Printf("Last error: %v\n", validationErrors.Last())

    // Categorized errors with consistent formatting
    fmt.Println("\n📋 Error Categories:")
    if emailErrors := validationErrors.Filter(contains("email")); emailErrors.Has() {
      fmt.Println("Email Issues:")
      if emailErrors.Count() == 1 {
        fmt.Println(customFormat([]error{emailErrors.First()}))
      } else {
        fmt.Println(emailErrors)
      }
    }
    if pwErrors := validationErrors.Filter(contains("password")); pwErrors.Has() {
      fmt.Println("Password Issues:")
      if pwErrors.Count() == 1 {
        fmt.Println(customFormat([]error{pwErrors.First()}))
      } else {
        fmt.Println(pwErrors)
      }
    }
    if ageErrors := validationErrors.Filter(contains("13 years")); ageErrors.Has() {
      fmt.Println("Age Restriction:")
      if ageErrors.Count() == 1 {
        fmt.Println(customFormat([]error{ageErrors.First()}))
      } else {
        fmt.Println(ageErrors)
      }
    }
  }

  // System Error Aggregation Example
  fmt.Println("\n=== System Error Aggregation ===")
  systemErrors := errors.NewMultiError(
    errors.WithLimit(5),
    errors.WithFormatter(systemErrorFormat),
  )

  // Simulate system errors
  systemErrors.Add(errors.New("database connection timeout").WithRetryable())
  systemErrors.Add(errors.New("API rate limit exceeded").WithRetryable())
  systemErrors.Add(errors.New("disk space low"))
  systemErrors.Add(errors.New("database connection timeout").WithRetryable()) // Duplicate
  systemErrors.Add(errors.New("cache miss"))
  systemErrors.Add(errors.New("database connection timeout").WithRetryable()) // Over limit

  fmt.Println(systemErrors)
  fmt.Printf("\nSystem Status: %d active issues\n", systemErrors.Count())

  // Filter retryable errors
  if retryable := systemErrors.Filter(errors.IsRetryable); retryable.Has() {
    fmt.Println("\n🔄 Retryable Errors:")
    fmt.Println(retryable)
  }
}

func systemErrorFormat(errs []error) string {
  var sb strings.Builder
  sb.WriteString("⚠️ System Alerts:\n")
  for i, err := range errs {
    sb.WriteString(fmt.Sprintf("  %d. %s", i+1, err))
    if errors.IsRetryable(err) {
      sb.WriteString(" (retryable)")
    }
    sb.WriteString("\n")
  }
  return sb.String()
}

func contains(substr string) func(error) bool {
  return func(err error) bool {
    return strings.Contains(err.Error(), substr)
  }
}
```

### Chain Execution

#### Sequential Task Processing
```go
package main

import (
  "fmt"
  "github.com/olekukonko/errors"
  "time"
)

// validateOrder checks order input.
func validateOrder() error {
  return nil // Simulate successful validation
}

// processKYC handles payment processing.
func processKYC() error {
  return nil // Simulate successful validation
}

// processPayment handles payment processing.
func processPayment() error {
  return errors.New("payment declined") // Simulate payment failure
}

// generateInvoice creates an invoice.
func generateInvoice() error {
  return errors.New("invoicing unavailable") // Simulate invoicing issue
}

// sendNotification sends a confirmation.
func sendNotification() error {
  return errors.New("notification failed") // Simulate notification failure
}

// processOrder simulates a multi-step order processing workflow.
func processOrder() error {
  c := errors.NewChain()

  // Validate order input
  c.Step(validateOrder).Tag("validation")

  // KYC  Process
  c.Step(validateOrder).Tag("validation")

  // Process payment with retries
  c.Step(processPayment).Tag("billing").Retry(3, 100*time.Millisecond)

  // Generate invoice
  c.Step(generateInvoice).Tag("invoicing")

  // Send notification (optional)
  c.Step(sendNotification).Tag("notification").Optional()

  return c.Run()
}

func main() {
  if err := processOrder(); err != nil {
    // Print error to stderr and exit
    errors.Inspect(err)
  }
  fmt.Println("Order processed successfully")
}
```

#### Sequential Task Processing 2
```go
package main

import (
	"fmt"
	"os"

	"github.com/olekukonko/errors"
)

// validate simulates a validation check that fails.
func validate(name string) error {
	return errors.Newf("validation for %s failed", name)
}

// validateOrder checks order input.
func validateOrder() error {
	return nil // Simulate successful validation
}

// verifyKYC handles Know Your Customer verification.
func verifyKYC(name string) error {
	return validate(name) // Simulate KYC validation failure
}

// processPayment handles payment processing.
func processPayment() error {
	return nil // Simulate successful payment
}

// processOrder coordinates the order processing workflow.
func processOrder() error {
	chain := errors.NewChain().
		Step(validateOrder).     // Step 1: Validate order
		Call(verifyKYC, "john"). // Step 2: Verify customer
		Step(processPayment)     // Step 3: Process payment

	if err := chain.Run(); err != nil {
		return errors.Errorf("processing order: %w", err)
	}
	return nil
}

func main() {
	if err := processOrder(); err != nil {
		// Print the full error chain to stderr
		fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
		// Output
		// ERROR: processing order: validation for john failed

		// For debugging, you could print the stack trace:
		// errors.Inspect(err)
		os.Exit(1)
	}

	fmt.Println("order processed successfully")
}

```


#### Retry with Timeout
```go
package main

import (
  "context"
  "fmt"
  "github.com/olekukonko/errors"
  "time"
)

func main() {
  c := errors.NewChain(
    errors.ChainWithTimeout(1*time.Second),
  ).
          Step(func() error {
            time.Sleep(2 * time.Second)
            return errors.New("fetch failed")
          }).
    Tag("api").
    Retry(3, 200*time.Millisecond)

  err := c.Run()
  if err != nil {
    var deadlineErr error
    if errors.As(err, &deadlineErr) && deadlineErr == context.DeadlineExceeded {
      fmt.Println("Fetch timed out")
    } else {
      fmt.Printf("Fetch failed: %v\n", err)
    }
    return
  }
  fmt.Println("Fetch succeeded")
}
```

#### Collecting All Errors
```go
package main

import (
  "fmt"
  "github.com/olekukonko/errors"
)

func main() {
  c := errors.NewChain(
    errors.ChainWithMaxErrors(2),
  ).
    Step(func() error { return errors.New("task 1 failed") }).Tag("task1").
    Step(func() error { return nil }).Tag("task2").
    Step(func() error { return errors.New("task 3 failed") }).Tag("task3")

  err := c.RunAll()
  if err != nil {
    errors.Inspect(err)
    return
  }
  fmt.Println("All tasks completed successfully")
}

```

---

## Using the `errmgr` Package

### Predefined Errors

#### Static Error
```go
package main

import (
	"fmt"
	"github.com/olekukonko/errors/errmgr"
)

func main() {
	// Use a predefined static error
	err := errmgr.ErrNotFound
	fmt.Println(err)        // Output: "not found"
	fmt.Println(err.Code()) // Output: 404
}
```

#### Templated Error
```go
package main

import (
	"fmt"
	"github.com/olekukonko/errors/errmgr"
)

func main() {
	// Use a templated error with category
	err := errmgr.ErrDBQuery("SELECT failed")
	fmt.Println(err)           // Output: "database query failed: SELECT failed"
	fmt.Println(err.Category()) // Output: "database"
}
```

### Error Monitoring

#### Basic Monitoring
```go
package main

import (
	"fmt"
	"github.com/olekukonko/errors/errmgr"
	"time"
)

func main() {
	// Define and monitor an error
	netErr := errmgr.Define("NetError", "network issue: %s")
	monitor := errmgr.NewMonitor("NetError")
	errmgr.SetThreshold("NetError", 2)
	defer monitor.Close()

	go func() {
		for alert := range monitor.Alerts() {
			fmt.Printf("Alert: %s, count: %d\n", alert.Error(), alert.Count())
		}
	}()

	for i := 0; i < 4; i++ {
		err := netErr(fmt.Sprintf("attempt %d", i))
		err.Free()
	}
	time.Sleep(100 * time.Millisecond)
}
```

#### Realistic Monitoring
```go
package main

import (
	"fmt"
	"github.com/olekukonko/errors"
	"github.com/olekukonko/errors/errmgr"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func main() {
	// Define our error types
	netErr := errmgr.Define("NetError", "network connection failed: %s (attempt %d)")
	dbErr := errmgr.Define("DBError", "database operation failed: %s")

	// Create monitors with different buffer sizes
	netMonitor := errmgr.NewMonitorBuffered("NetError", 10) // Larger buffer for network errors
	dbMonitor := errmgr.NewMonitorBuffered("DBError", 5)    // Smaller buffer for DB errors
	defer netMonitor.Close()
	defer dbMonitor.Close()

	// Set different thresholds
	errmgr.SetThreshold("NetError", 3) // Alert after 3 network errors
	errmgr.SetThreshold("DBError", 2)  // Alert after 2 database errors

	// Set up signal handling for graceful shutdown
	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)

	// Alert handler goroutine
	done := make(chan struct{})
	go func() {
		defer close(done)
		for {
			select {
			case alert, ok := <-netMonitor.Alerts():
				if !ok {
					fmt.Println("Network alert channel closed")
					return
				}
				handleAlert("NETWORK", alert)
			case alert, ok := <-dbMonitor.Alerts():
				if !ok {
					fmt.Println("Database alert channel closed")
					return
				}
				handleAlert("DATABASE", alert)
			case <-time.After(2 * time.Second):
				// Periodic check for shutdown
				continue
			}
		}
	}()

	// Simulate operations with potential failures
	go func() {
		for i := 1; i <= 15; i++ {
			// Simulate different error scenarios
			if i%4 == 0 {
				// Database error
				err := dbErr("connection timeout")
				fmt.Printf("DB Operation %d: Failed\n", i)
				err.Free()
			} else {
				// Network error
				var errMsg string
				switch {
				case i%3 == 0:
					errMsg = "timeout"
				case i%5 == 0:
					errMsg = "connection reset"
				default:
					errMsg = "unknown error"
				}

				err := netErr(errMsg, i)
				fmt.Printf("Network Operation %d: Failed with %q\n", i, errMsg)
				err.Free()
			}

			// Random delay between operations
			time.Sleep(time.Duration(100+(i%200)) * time.Millisecond)
		}
	}()

	// Wait for shutdown signal or completion
	select {
	case <-sigChan:
		fmt.Println("\nReceived shutdown signal...")
	case <-time.After(5 * time.Second):
		fmt.Println("Completion timeout reached...")
	}

	// Cleanup
	fmt.Println("Initiating shutdown...")
	netMonitor.Close()
	dbMonitor.Close()

	// Wait for the alert handler to finish
	select {
	case <-done:
		fmt.Println("Alert handler shutdown complete")
	case <-time.After(1 * time.Second):
		fmt.Println("Alert handler shutdown timeout")
	}

	fmt.Println("Application shutdown complete")
}

func handleAlert(service string, alert *errors.Error) {
	if alert == nil {
		fmt.Printf("[%s] Received nil alert\n", service)
		return
	}

	fmt.Printf("[%s ALERT] %s (total occurrences: %d)\n",
		service, alert.Error(), alert.Count())

	if alert.Count() > 5 {
		fmt.Printf("[%s CRITICAL] High error rate detected!\n", service)
	}
}
```

---

## Performance Optimization

### Configuration Tuning
```go
package main

import (
	"fmt"
	"github.com/olekukonko/errors"
)

func main() {
	// Tune error package configuration
	errors.Configure(errors.Config{
		StackDepth:     32,    // Limit stack frames
		ContextSize:    4,     // Optimize small contexts
		DisablePooling: false, // Enable pooling
	})
	err := errors.New("configured error")
	fmt.Println(err) // Output: "configured error"
}
```

### Using `Free()` for Performance
```go
package main

import (
	"fmt"
	"github.com/olekukonko/errors"
)

func main() {
	// Use Free() to return error to pool
	err := errors.New("temp error")
	fmt.Println(err) // Output: "temp error"
	err.Free()       // Immediate pool return, reduces GC pressure
}
```

### Benchmarks
Real performance data (Apple M3 Pro, Go 1.21):
```
goos: darwin
goarch: arm64
pkg: github.com/olekukonko/errors
cpu: Apple M3 Pro
BenchmarkBasic_New-12            99810412    12.00 ns/op    0 B/op    0 allocs/op
BenchmarkStack_WithStack-12      5879510    205.6 ns/op   24 B/op    1 allocs/op
BenchmarkContext_Small-12       29600850    40.34 ns/op   16 B/op    1 allocs/op
BenchmarkWrapping_Simple-12    100000000    11.73 ns/op    0 B/op    0 allocs/op
```
- **New with Pooling**: 12 ns/op, 0 allocations
- **WithStack**: 205 ns/op, minimal allocation
- **Context**: 40 ns/op for small contexts
- Run: `go test -bench=. -benchmem`

## Migration Guide

### From Standard Library
```go
package main

import (
	"fmt"
	"github.com/olekukonko/errors"
)

func main() {
	// Before: Standard library error
	err1 := fmt.Errorf("error: %v", "oops")
	fmt.Println(err1)

	// After: Enhanced error with context and stack
	err2 := errors.Newf("error: %v", "oops").
		With("source", "api").
		WithStack()
	fmt.Println(err2)
}
```

### From `pkg/errors`
```go
package main

import (
  "fmt"
  "github.com/olekukonko/errors"
)

func main() {
  // Before: pkg/errors (assuming similar API)
  // err := pkgerrors.Wrap(err, "context")

  // After: Enhanced wrapping
  err := errors.New("low-level").
    Msgf("context: %s", "details").
    WithStack()
  fmt.Println(err)
}
```

### Compatibility with `errors.Is` and `errors.As`
```go
package main

import (
	"fmt"
	"github.com/olekukonko/errors"
)

func main() {
	// Check compatibility with standard library
	err := errors.Named("MyError")
	wrapped := errors.Wrapf(err, "outer")
	if errors.Is(wrapped, err) { // Stdlib compatible
		fmt.Println("Matches MyError") // Output: "Matches MyError"
	}
}
```

## FAQ

- **When to use `Copy()`?**
  - Use ` SOCIALCopy()` to create a modifiable duplicate of an error without altering the original.

- **When to use `Free()`?**
  - Use in performance-critical loops; otherwise, autofree handles it (Go 1.24+).

- **How to handle cleanup?**
  - Use `Callback()` for automatic actions like rollbacks or logging.

- **How to add stack traces later?**
  - Use `WithStack()` to upgrade a simple error:
    ```go
    package main

    import (
        "fmt"
        "github.com/olekukonko/errors"
    )

    func main() {
        err := errors.New("simple")
        err = err.WithStack()
        fmt.Println(err.Stack())
    }
    ```

## Contributing
- Fork, branch, commit, and PR—see [CONTRIBUTING.md](#).

## License
MIT License - See [LICENSE](LICENSE).