Repository navigation
Expand file tree
/
Copy pathexample_test.go
More file actions
93 lines (74 loc) · 2.09 KB
/
Copy pathexample_test.go
File metadata and controls
93 lines (74 loc) · 2.09 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
package efmt_test
import (
"context"
"errors"
"fmt"
"log/slog"
"os"
"github.com/vasilesk/efmt"
)
var errNotFound = errors.New("not found")
func findUser(id int) error {
return efmt.Wrap(errNotFound, "user lookup failed", efmt.KV("user_id", id))
}
func ExampleNew() {
err := efmt.New("user is underage", efmt.KV("age", 16), efmt.KV("required_age", 18))
fmt.Println(err)
fmt.Println(efmt.Values(err))
// Output:
// user is underage
// map[age:16 required_age:18]
}
func ExampleWrap() {
err := efmt.Wrap(findUser(42), "request failed", efmt.KV("request_id", "abc"))
fmt.Println(err)
fmt.Println(errors.Is(err, errNotFound))
fmt.Println(efmt.Values(err))
// Output:
// request failed: user lookup failed: not found
// true
// map[request_id:abc user_id:42]
}
func ExampleValue() {
err := findUser(42)
if id, ok := efmt.Value[int](err, "user_id"); ok {
fmt.Println("user id:", id)
}
if _, ok := efmt.Value[string](err, "user_id"); !ok {
fmt.Println("user id is not a string")
}
// Output:
// user id: 42
// user id is not a string
}
func ExampleValues_override() {
inner := efmt.New("inner", efmt.KV("stage", "parse"), efmt.KV("line", 7))
outer := efmt.Wrap(inner, "outer", efmt.KV("stage", "load"))
fmt.Println(efmt.Values(outer))
// Output:
// map[line:7 stage:load]
}
func ExampleValues_join() {
err := errors.Join(
efmt.New("first", efmt.KV("first", 1)),
fmt.Errorf("second: %w", efmt.New("inner", efmt.KV("second", 2))),
)
fmt.Println(efmt.Values(err))
// Output:
// map[first:1 second:2]
}
func ExampleAttrs() {
logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey {
return slog.Attr{}
}
return a
},
}))
err := efmt.Wrap(findUser(42), "request failed", efmt.KV("request_id", "abc"))
attrs := append(efmt.Attrs(err), slog.Any("error", err))
logger.LogAttrs(context.Background(), slog.LevelError, "request failed", attrs...)
// Output:
// level=ERROR msg="request failed" request_id=abc user_id=42 error="request failed: user lookup failed: not found"
}