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 fmt.Println(err.(interface{ Unwrap() []error }).Unwrap())
70
71
72
73
74
75
76 }
77
78 func ExampleIs() {
79 if _, err := os.Open("non-existing"); err != nil {
80 if errors.Is(err, fs.ErrNotExist) {
81 fmt.Println("file does not exist")
82 } else {
83 fmt.Println(err)
84 }
85 }
86
87
88
89 }
90
91 func ExampleAs() {
92 if _, err := os.Open("non-existing"); err != nil {
93 var pathError *fs.PathError
94 if errors.As(err, &pathError) {
95 fmt.Println("Failed at path:", pathError.Path)
96 } else {
97 fmt.Println(err)
98 }
99 }
100
101
102
103 }
104
105 func ExampleUnwrap() {
106 err1 := errors.New("error1")
107 err2 := fmt.Errorf("error2: [%w]", err1)
108 fmt.Println(err2)
109 fmt.Println(errors.Unwrap(err2))
110
111
112
113 }
114
View as plain text