-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_test.go
More file actions
89 lines (76 loc) · 1.98 KB
/
Copy pathexample_test.go
File metadata and controls
89 lines (76 loc) · 1.98 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
package errx_test
import (
"errors"
"fmt"
"github.com/ubgo/errx"
)
func Example() {
err := errx.New("db: deadlock on user_orders").
WithDomain("billing").
WithCode("TX_RETRY").
WithPublic("Something went wrong, please retry").
WithRetryable(0)
fmt.Println(err.Error())
fmt.Println(err.Public("unknown"))
fmt.Println(errx.Code(err))
fmt.Println(errx.IsRetryable(err))
// Output:
// db: deadlock on user_orders
// Something went wrong, please retry
// TX_RETRY
// true
}
func ExampleWrap() {
sentinel := errors.New("pq: deadlock")
err := errx.Wrap(sentinel, "load orders").WithCode("DB_READ")
fmt.Println(err.Error())
fmt.Println(errors.Is(err, sentinel)) // transparent by default
fmt.Println(errx.Code(err))
// Output:
// load orders: pq: deadlock
// true
// DB_READ
}
func ExampleError_Opaque() {
sentinel := errors.New("secret dependency sentinel")
err := errx.Wrap(sentinel, "public boundary").Opaque()
fmt.Println(errors.Is(err, sentinel)) // barrier hides the cause
// Output:
// false
}
func ExampleAccumulate() {
err := errx.Accumulate(
func() error { return nil },
func() error { return errors.New("name is required") },
func() error { return errors.New("email is invalid") },
)
fmt.Println(errx.Code(err))
fmt.Println(len(errx.Get(err).Suppressed()))
// Output:
// VALIDATION
// 2
}
func ExampleNote() {
base := errx.New("upstream timeout").WithCode("TIMEOUT")
_ = errx.Note(base, "attempt", 3) // no extra wrapper frame
for _, f := range base.Fields() {
fmt.Printf("%s=%v\n", f.Key, f.Value)
}
// Output:
// attempt=3
}
func ExampleEncode() {
orig := errx.New("internal detail").
WithDomain("billing").WithCode("NOT_FOUND").
WithPublic("Order not found").
With("password", "hunter2") // unsafe: never serialized
blob, _ := errx.Encode(orig)
got, _ := errx.Decode(blob)
fmt.Println(errx.Code(got))
fmt.Println(got.Public("x"))
fmt.Println(got.Fingerprint() == orig.Fingerprint())
// Output:
// NOT_FOUND
// Order not found
// true
}