Skip to content

Commit 36dafdb

Browse files
committed
add errors Match and IsAny
Simplified examples
1 parent b3d0973 commit 36dafdb

File tree

1 file changed

+19
-40
lines changed

1 file changed

+19
-40
lines changed

src/errors/example_test.go

Lines changed: 19 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -125,55 +125,34 @@ func ExampleUnwrap() {
125125
}
126126

127127
func ExampleIsAny() {
128-
var (
129-
ErrNotFound = errors.New("not found")
130-
ErrPermission = errors.New("permission denied")
131-
ErrTimeout = errors.New("timeout")
132-
)
133-
134-
// Simulate receiving an error
135-
err := fmt.Errorf("database query failed: %w", ErrTimeout)
136-
137-
// Check if the error matches any of the known errors
138-
if errors.IsAny(err, ErrNotFound, ErrPermission, ErrTimeout) {
139-
fmt.Println("error is one of the expected types")
140-
}
141-
142-
// Check against a different set
143-
if !errors.IsAny(err, ErrNotFound, ErrPermission) {
144-
fmt.Println("error is not a not-found or permission error")
128+
if _, err := os.Open("non-existing"); err != nil {
129+
if errors.IsAny(err, fs.ErrNotExist, fs.ErrInvalid) {
130+
fmt.Println("file does not exist")
131+
} else {
132+
fmt.Println(err)
133+
}
145134
}
146-
147135
// Output:
148-
// error is one of the expected types
149-
// error is not a not-found or permission error
136+
// file does not exist
150137
}
151138

152139
func ExampleMatch() {
153-
var (
154-
ErrNotFound = errors.New("not found")
155-
ErrNetworkIssue = errors.New("network issue")
156-
ErrDiskFull = errors.New("disk full")
157-
)
140+
_, err := os.Open("non-existing")
158141

159-
err := fmt.Errorf("operation failed: %w", ErrNetworkIssue)
160-
161-
// Match returns the matched error from the targets
162-
if matched := errors.Match(err, ErrNotFound, ErrNetworkIssue, ErrDiskFull); matched != nil {
142+
matched := errors.Match(err, fs.ErrNotExist, fs.ErrInvalid)
143+
if matched != nil {
163144
fmt.Println("matched error:", matched)
145+
} else {
146+
fmt.Println("no match")
164147
}
165148

166-
// Can be used in a switch statement
167-
switch errors.Match(err, ErrNotFound, ErrNetworkIssue, ErrDiskFull) {
168-
case ErrNotFound:
169-
fmt.Println("resource not found")
170-
case ErrNetworkIssue:
171-
fmt.Println("network issue detected")
172-
case ErrDiskFull:
173-
fmt.Println("disk is full")
149+
switch matched {
150+
case fs.ErrNotExist:
151+
fmt.Println("file does not exist")
152+
case fs.ErrInvalid:
153+
fmt.Println("invalid argument")
174154
}
175-
176155
// Output:
177-
// matched error: network issue
178-
// network issue detected
156+
// matched error: file does not exist
157+
// file does not exist
179158
}

0 commit comments

Comments
 (0)