Source file
src/errors/example_test.go
1
2
3
4
5 package errors_test
6
7 import (
8 "errors"
9 "fmt"
10 "io/fs"
11 "os"
12 "time"
13 )
14
15
16 type MyError struct {
17 When time.Time
18 What string
19 }
20
21 func (e MyError) Error() string {
22 return fmt.Sprintf("%v: %v", e.When, e.What)
23 }
24
25 func oops() error {
26 return MyError{
27 time.Date(1989, 3, 15, 22, 30, 0, 0, time.UTC),
28 "the file system has gone away",
29 }
30 }
31
32 func Example() {
33 if err := oops(); err != nil {
34 fmt.Println(err)
35 }
36
37 }
38
39 func ExampleNew() {
40 err := errors.New("emit macho dwarf: elf header corrupted")
41 if err != nil {
42 fmt.Print(err)
43 }
44
45 }
46
47
48
49 func ExampleNew_errorf() {
50 const name, id = "bimmler", 17
51 err := fmt.Errorf("user %q (id %d) not found", name, id)
52 if err != nil {
53 fmt.Print(err)
54 }
55
56 }
57
58 func ExampleJoin() {
59 err1 := errors.New("err1")
60 err2 := errors.New("err2")
61 err := errors.Join(err1, err2)
62 fmt.Println(err)
63 if errors.Is(err, err1) {
64 fmt.Println("err is err1")
65 }
66 if errors.Is(err, err2) {
67 fmt.Println("err is err2")
68 }
69
70
71
72
73
74 }
75
76 func ExampleIs() {
77 if _, err := os.Open("non-existing"); err != nil {
78 if errors.Is(err, fs.ErrNotExist) {
79 fmt.Println("file does not exist")
80 } else {
81 fmt.Println(err)
82 }
83 }
84
85
86
87 }
88
89 func ExampleAs() {
90 if _, err := os.Open("non-existing"); err != nil {
91 var pathError *fs.PathError
92 if errors.As(err, &pathError) {
93 fmt.Println("Failed at path:", pathError.Path)
94 } else {
95 fmt.Println(err)
96 }
97 }
98
99
100
101 }
102
103 func ExampleUnwrap() {
104 err1 := errors.New("error1")
105 err2 := fmt.Errorf("error2: [%w]", err1)
106 fmt.Println(err2)
107 fmt.Println(errors.Unwrap(err2))
108
109
110
111 }
112
View as plain text