-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_test.go
More file actions
44 lines (37 loc) · 919 Bytes
/
example_test.go
File metadata and controls
44 lines (37 loc) · 919 Bytes
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
package errctx
import (
"fmt"
)
type recoverableError struct{}
func (recoverableError) Error() string {
return "recoverableError"
}
func doX() error {
// Try to do X, but it fails...
return New("could not do X: bad stuff happened")
// This is essentially equivalent to:
// return errors.New("could not do X: bad stuff happened")
}
func doY() error {
//...
// Doing Y depends on doing X:
if err := doX(); err != nil {
return WithCtx(err, "could not do Y")
}
//...
return nil
}
func Example() {
//...
if err := doY(); err != nil {
// You can inspect the root error and act depending on its type.
if _, ok := Root(err).(recoverableError); ok {
// If the error is a recoverableError (it never is), we do not prematurely exit the program.
} else {
fmt.Println(err.Error())
return // Premature program exit.
}
}
//...
// Output: could not do Y: could not do X: bad stuff happened
}