Repository navigation
Expand file tree
/
Copy pathexample_test.go
More file actions
567 lines (447 loc) · 16.6 KB
/
Copy pathexample_test.go
File metadata and controls
567 lines (447 loc) · 16.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
package errx_test
import (
"context"
"errors"
"fmt"
"io"
"log/slog"
"os"
"strings"
"github.com/go-extras/errx"
)
// Example demonstrates basic usage of classification tags
func Example() {
// Define classification tags
ErrNotFound := errx.NewSentinel("resource not found")
// Create an error and classify it
err := errors.New("record missing")
classifiedErr := errx.Classify(err, ErrNotFound)
// Check the classification
if errors.Is(classifiedErr, ErrNotFound) {
fmt.Println("Error is classified as not found")
}
// Output:
// Error is classified as not found
}
func ExampleSentinelParents() {
ErrDatabase := errx.NewSentinel("database")
ErrTimeout := errx.NewSentinel("timeout", ErrDatabase)
for _, parent := range errx.SentinelParents(ErrTimeout) {
fmt.Println(parent.Error())
}
// Output:
// database
}
// ExampleWrap demonstrates wrapping errors with context and tags
func ExampleWrap() {
ErrDatabase := errx.NewSentinel("database error")
err := errors.New("connection timeout")
wrapped := errx.Wrap("failed to query database", err, ErrDatabase)
fmt.Println(wrapped.Error())
fmt.Println("Is database error:", errors.Is(wrapped, ErrDatabase))
// Output:
// failed to query database: connection timeout
// Is database error: true
}
// ExampleClassify demonstrates classifying errors without adding context
func ExampleClassify() {
ErrValidation := errx.NewSentinel("validation error")
err := errors.New("invalid email format")
classified := errx.Classify(err, ErrValidation)
fmt.Println(classified.Error())
fmt.Println("Is validation error:", errors.Is(classified, ErrValidation))
// Output:
// invalid email format
// Is validation error: true
}
// ExampleClassifyNew demonstrates creating and classifying an error in one step
func ExampleClassifyNew() {
ErrDatabase := errx.NewSentinel("database error")
ErrRetryable := errx.NewSentinel("retryable error")
// Create a new error and classify it in one step
err := errx.ClassifyNew("connection timeout", ErrDatabase, ErrRetryable)
fmt.Println(err.Error())
fmt.Println("Is database error:", errors.Is(err, ErrDatabase))
fmt.Println("Is retryable:", errors.Is(err, ErrRetryable))
// Output:
// connection timeout
// Is database error: true
// Is retryable: true
}
// ExampleClassifyNew_withDisplayable demonstrates ClassifyNew with displayable errors
func ExampleClassifyNew_withDisplayable() {
ErrNotFound := errx.NewSentinel("not found")
displayErr := errx.NewDisplayable("The requested resource was not found")
// Create error with both classification and displayable message
err := errx.ClassifyNew("user record missing from database", ErrNotFound, displayErr)
// Full error for logging
fmt.Println("Full error:", err.Error())
// User-facing message
fmt.Println("Display text:", errx.DisplayText(err))
// Classification check
fmt.Println("Is not found:", errors.Is(err, ErrNotFound))
// Output:
// Full error: user record missing from database
// Display text: The requested resource was not found
// Is not found: true
}
// ExampleNewSentinel_multipleParents demonstrates creating a sentinel with multiple parent sentinels
func ExampleNewSentinel_multipleParents() {
// Create independent classification dimensions
ErrRetryable := errx.NewSentinel("retryable")
ErrDatabase := errx.NewSentinel("database")
// Create a tag that inherits from both
ErrDatabaseTimeout := errx.NewSentinel("database timeout", ErrDatabase, ErrRetryable)
err := errx.Wrap("query failed", errors.New("connection timeout"), ErrDatabaseTimeout)
// Can check for specific error
if errors.Is(err, ErrDatabaseTimeout) {
fmt.Println("Specific: database timeout")
}
// Can check for database errors
if errors.Is(err, ErrDatabase) {
fmt.Println("Category: database error")
}
// Can check for retryable errors
if errors.Is(err, ErrRetryable) {
fmt.Println("Behavior: retryable error")
}
// Output:
// Specific: database timeout
// Category: database error
// Behavior: retryable error
}
// ExampleNewDisplayable demonstrates creating displayable errors
func ExampleNewDisplayable() {
displayErr := errx.NewDisplayable("User not found")
fmt.Println(displayErr.Error())
fmt.Println("Is displayable:", errx.IsDisplayable(displayErr))
// Output:
// User not found
// Is displayable: true
}
// ExampleDisplayText demonstrates extracting displayable messages
func ExampleDisplayText() {
displayErr := errx.NewDisplayable("Invalid email address")
wrapped := errx.Wrap("validation failed", displayErr)
// Extract just the displayable message
msg := errx.DisplayText(wrapped)
fmt.Println("Display message:", msg)
// Full error for logging
fmt.Println("Full error:", wrapped.Error())
// Output:
// Display message: Invalid email address
// Full error: validation failed: Invalid email address
}
// ExampleDisplayTextDefault demonstrates extracting displayable messages with fallback
func ExampleDisplayTextDefault() {
// Error with displayable message - returns the displayable message
displayErr := errx.NewDisplayable("Invalid email address")
wrapped := errx.Wrap("validation failed", displayErr)
msg1 := errx.DisplayTextDefault(wrapped, "An error occurred")
fmt.Println("With displayable:", msg1)
// Error without displayable message - returns the default
regularErr := errors.New("database connection timeout")
msg2 := errx.DisplayTextDefault(regularErr, "Service temporarily unavailable")
fmt.Println("Without displayable:", msg2)
// Nil error - returns empty string
msg3 := errx.DisplayTextDefault(nil, "Default message")
fmt.Printf("Nil error: %q\n", msg3)
// Output:
// With displayable: Invalid email address
// Without displayable: Service temporarily unavailable
// Nil error: ""
}
// ExampleAttrs demonstrates adding structured attributes to errors
func ExampleAttrs() {
attrErr := errx.Attrs(
"user_id", 12345,
"action", "delete",
"resource", "account",
)
attrs := errx.ExtractAttrs(attrErr)
for _, attr := range attrs {
fmt.Printf("%s=%v ", attr.Key, attr.Value)
}
// Output:
// user_id=12345 action=delete resource=account
}
// Example_combinedUsage demonstrates combining all features
func Example_combinedUsage() {
// Define tags
ErrNotFound := errx.NewSentinel("not found")
// Create error with attributes
baseErr := errors.New("record not found in database")
attrErr := errx.Attrs("table", "users", "id", 123)
// Classify the error
classifiedErr := errx.Classify(baseErr, attrErr, ErrNotFound)
// Add displayable message
displayErr := errx.NewDisplayable("User not found")
finalErr := errx.Classify(classifiedErr, displayErr)
// Check classification
fmt.Println("Is not found:", errors.Is(finalErr, ErrNotFound))
// Get displayable message
fmt.Println("Display:", errx.DisplayText(finalErr))
// Extract attributes
attrs := errx.ExtractAttrs(finalErr)
fmt.Printf("Attributes: %d found\n", len(attrs))
// Output:
// Is not found: true
// Display: User not found
// Attributes: 2 found
}
// ExampleIsDisplayable demonstrates checking if an error has a displayable message
func ExampleIsDisplayable() {
displayErr := errx.NewDisplayable("Operation failed")
regularErr := errors.New("internal error")
fmt.Println("Display error is displayable:", errx.IsDisplayable(displayErr))
fmt.Println("Regular error is displayable:", errx.IsDisplayable(regularErr))
// Output:
// Display error is displayable: true
// Regular error is displayable: false
}
// ExampleHasAttrs demonstrates checking if an error has attributes
func ExampleHasAttrs() {
attrErr := errx.Attrs("key", "value")
regularErr := errors.New("no attributes")
fmt.Println("Attr error has attrs:", errx.HasAttrs(attrErr))
fmt.Println("Regular error has attrs:", errx.HasAttrs(regularErr))
// Output:
// Attr error has attrs: true
// Regular error has attrs: false
}
// Example_apiHandler demonstrates a practical API error handling pattern
func Example_apiHandler() {
// Define error tags
ErrNotFound := errx.NewSentinel("not found")
ErrValidation := errx.NewSentinel("validation")
// Simulate an error from the service layer
var serviceErr error
serviceErr = errx.NewDisplayable("Email is required")
serviceErr = errx.Classify(serviceErr, ErrValidation)
serviceErr = errx.Classify(serviceErr, errx.Attrs("field", "email"))
// API handler logic
statusCode := 500
if errors.Is(serviceErr, ErrNotFound) {
statusCode = 404
} else if errors.Is(serviceErr, ErrValidation) {
statusCode = 400
}
message := "An error occurred"
if errx.IsDisplayable(serviceErr) {
message = errx.DisplayText(serviceErr)
}
fmt.Printf("HTTP %d: %s\n", statusCode, message)
// Log with attributes
if errx.HasAttrs(serviceErr) {
attrs := errx.ExtractAttrs(serviceErr)
fmt.Printf("Attributes: %v\n", attrs)
}
// Output:
// HTTP 400: Email is required
// Attributes: field=email
}
// ExampleFromAttrMap demonstrates creating attributes from a map
func ExampleFromAttrMap() {
attrs := map[string]any{
"user_id": 42,
"ip": "192.168.1.1",
"endpoint": "/api/users",
}
attrErr := errx.FromAttrMap(attrs)
extracted := errx.ExtractAttrs(attrErr)
fmt.Printf("Total attributes: %d\n", len(extracted))
fmt.Println("Has attrs:", errx.HasAttrs(attrErr))
// Output:
// Total attributes: 3
// Has attrs: true
}
// ExampleExtractAttrs demonstrates extracting attributes from nested errors
func ExampleExtractAttrs() {
// Create error with attributes
baseErr := errors.New("database connection failed")
attrErr := errx.Attrs("host", "localhost", "port", 5432)
classified := errx.Classify(baseErr, attrErr)
// Wrap it further
wrapped := fmt.Errorf("startup failed: %w", classified)
// Extract attributes from anywhere in the chain
attrs := errx.ExtractAttrs(wrapped)
fmt.Printf("Extracted %d attributes\n", len(attrs))
for _, attr := range attrs {
fmt.Printf("%s: %v\n", attr.Key, attr.Value)
}
// Output:
// Extracted 2 attributes
// host: localhost
// port: 5432
}
// Example_richError demonstrates creating a fully-featured error
func Example_richError() {
// Define classification hierarchy
ErrDatabase := errx.NewSentinel("database")
ErrRetryable := errx.NewSentinel("retryable")
ErrDBTimeout := errx.NewSentinel("db timeout", ErrDatabase, ErrRetryable)
// Create base error
baseErr := errors.New("connection timeout after 30s")
// Add user-facing message
displayErr := errx.NewDisplayable("The service is temporarily unavailable")
// Add structured context
attrErr := errx.Attrs(
"database", "users",
"operation", "read",
"timeout_seconds", 30,
)
// Combine everything
finalErr := errx.Wrap("query execution failed", baseErr, displayErr, attrErr, ErrDBTimeout)
// Use the error
fmt.Println("Classification checks:")
fmt.Println(" Is database error:", errors.Is(finalErr, ErrDatabase))
fmt.Println(" Is retryable:", errors.Is(finalErr, ErrRetryable))
fmt.Println("\nUser message:", errx.DisplayText(finalErr))
fmt.Println("\nLogging context:")
if errx.HasAttrs(finalErr) {
attrs := errx.ExtractAttrs(finalErr)
for _, attr := range attrs {
fmt.Printf(" %s: %v\n", attr.Key, attr.Value)
}
}
fmt.Println("\nFull error:", finalErr.Error())
// Output:
// Classification checks:
// Is database error: true
// Is retryable: true
//
// User message: The service is temporarily unavailable
//
// Logging context:
// database: users
// operation: read
// timeout_seconds: 30
//
// Full error: query execution failed: connection timeout after 30s
}
// Example_errorChain demonstrates working with error chains
func Example_errorChain() {
ErrValidation := errx.NewSentinel("validation")
// Build an error chain
err1 := errors.New("field is empty")
err2 := errx.Classify(err1, ErrValidation)
err3 := errx.Wrap("validation failed", err2)
err4 := fmt.Errorf("request processing: %w", err3)
// Check classification through the chain
fmt.Println("Is validation error:", errors.Is(err4, ErrValidation))
// Add displayable at any level
displayErr := errx.NewDisplayable("Please provide a valid value")
err5 := errx.Classify(err4, displayErr)
// Display message found through chain
fmt.Println("Display text:", errx.DisplayText(err5))
fmt.Println("Full error:", err5.Error())
// Output:
// Is validation error: true
// Display text: Please provide a valid value
// Full error: request processing: validation failed: field is empty
}
// Example_apiHandlerWithDefault demonstrates using DisplayTextDefault in an API handler
func Example_apiHandlerWithDefault() {
// Define error sentinels
ErrNotFound := errx.NewSentinel("not found")
ErrDatabase := errx.NewSentinel("database")
// Simulate different error scenarios
type errorCase struct {
name string
err error
}
cases := []errorCase{
{
name: "displayable error",
err: errx.Wrap("user lookup failed", errx.NewDisplayable("User not found"), ErrNotFound),
},
{
name: "internal error",
err: errx.Wrap("query failed", errors.New("connection timeout"), ErrDatabase),
},
}
for _, tc := range cases {
// Using DisplayTextDefault provides consistent fallback behavior
message := errx.DisplayTextDefault(tc.err, "An unexpected error occurred")
fmt.Printf("%s: %s\n", tc.name, message)
}
// Output:
// displayable error: User not found
// internal error: An unexpected error occurred
}
// ExampleAttrList_ToSlogAttrs demonstrates converting errx.AttrList to slog.Attr
// for use with LogAttrs. The expected output is rendered via a small in-test
// handler we control so the example does not depend on the stdlib
// slog.TextHandler format (which may shift between Go versions).
func ExampleAttrList_ToSlogAttrs() {
// Create an error with attributes
err := errx.Attrs("user_id", 123, "action", "delete", "resource", "account")
wrappedErr := errx.Wrap("operation failed", err)
// Extract attributes from the error
attrs := errx.ExtractAttrs(wrappedErr)
// Convert to slog.Attr for use with LogAttrs (most efficient)
slogAttrs := attrs.ToSlogAttrs()
// Use with slog logger backed by an example-controlled handler so the
// // Output: assertion below stays stable across Go versions.
logger := slog.New(newExampleHandler(os.Stdout))
// LogAttrs accepts ...slog.Attr directly
logger.LogAttrs(context.Background(), slog.LevelError, "operation failed", slogAttrs...)
// Output:
// ERROR operation failed user_id=123 action=delete resource=account
}
// ExampleAttrList_ToSlogArgs demonstrates converting errx.AttrList to []any
// for use with slog convenience methods. As with ExampleAttrList_ToSlogAttrs,
// the output format is controlled by an in-test handler to remain stable.
func ExampleAttrList_ToSlogArgs() {
// Create an error with attributes
err := errx.Attrs("user_id", 123, "action", "delete", "resource", "account")
wrappedErr := errx.Wrap("operation failed", err)
// Extract attributes from the error
attrs := errx.ExtractAttrs(wrappedErr)
// Convert to []any for use with Error/Info/Warn methods
slogArgs := attrs.ToSlogArgs()
// Use with slog logger backed by an example-controlled handler.
logger := slog.New(newExampleHandler(os.Stdout))
// Error/Info/Warn methods accept ...any
logger.Error("operation failed", slogArgs...)
// Output:
// ERROR operation failed user_id=123 action=delete resource=account
}
// ExampleJoin demonstrates aggregating multiple errors into one and classifying
// the aggregate via the existing API. Attributes from every joined branch, plus
// the group-level classification, all remain inspectable.
func ExampleJoin() {
ErrBatch := errx.NewSentinel("batch failed")
// Two independent failures, each carrying its own attribute.
item1 := errx.Classify(errors.New("item 1 failed"), errx.Attrs("index", 0))
item2 := errx.Classify(errors.New("item 2 failed"), errx.Attrs("index", 1))
// Join them, then classify the aggregate as a batch failure.
err := errx.Classify(errx.Join(item1, item2), ErrBatch)
fmt.Println(errors.Is(err, ErrBatch))
fmt.Println(err.Error())
// Output:
// true
// item 1 failed
// item 2 failed
}
// exampleHandler is a minimal slog.Handler used by the slog examples to keep
// their // Output: assertions stable across Go versions. It prints records as
// "<LEVEL> <message> [k=v...]" without timestamps.
type exampleHandler struct {
w io.Writer
}
func newExampleHandler(w io.Writer) *exampleHandler { return &exampleHandler{w: w} }
func (*exampleHandler) Enabled(context.Context, slog.Level) bool { return true }
func (h *exampleHandler) Handle(_ context.Context, r slog.Record) error {
var b strings.Builder
fmt.Fprintf(&b, "%s %s", r.Level.String(), r.Message)
r.Attrs(func(a slog.Attr) bool {
fmt.Fprintf(&b, " %s=%v", a.Key, a.Value.Any())
return true
})
b.WriteByte('\n')
_, err := io.WriteString(h.w, b.String())
return err
}
func (h *exampleHandler) WithAttrs([]slog.Attr) slog.Handler { return h }
func (h *exampleHandler) WithGroup(string) slog.Handler { return h }