Debian Codegraph @

src/errors/example_test.go

raw
1 // Copyright 2012 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package errors_test
6
7 import (
8 "errors"
9 "fmt"
10 "io/fs"
11 "os"
12 "time"
13 )
14
15 // MyError is an error implementation that includes a time and message.
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 // Output: 1989-03-15 22:30:00 +0000 UTC: the file system has gone away
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 // Output: emit macho dwarf: elf header corrupted
45 }
46
47 // The fmt package's Errorf function lets us use the package's formatting
48 // features to create descriptive error messages.
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 // Output: user "bimmler" (id 17) not found
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 // Output:
71 // err1
72 // err2
73 // err is err1
74 // err is err2
75 // [err1 err2]
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 // Output:
88 // file does not exist
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 // Output:
102 // Failed at path: non-existing
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 // Output:
111 // error2: [error1]
112 // error1
113 }