-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy patherrors.go
57 lines (46 loc) · 1.01 KB
/
errors.go
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
45
46
47
48
49
50
51
52
53
54
55
56
57
// Copyright (c) Efficient Go Authors
// Licensed under the Apache License 2.0.
package main
import "github.com/efficientgo/core/errors"
// Examples of error handling and different return arguments.
// Read more in "Efficient Go"; Example 2-4.
func shouldFail() bool { return false }
func noErrCanHappen() int {
// ...
return 204
}
func doOrErr() error {
// ...
if shouldFail() {
return errors.New("ups, XYZ failed")
}
return nil
}
func intOrErr() (int, error) {
// ...
if shouldFail() {
return 0, errors.New("ups, XYZ2 failed")
}
return noErrCanHappen(), nil
}
// Examples of handling different return arguments.
// Read more in "Efficient Go"; Example 2-5.
func main() {
ret := noErrCanHappen()
if err := nestedDoOrErr(); err != nil {
// handle error
}
ret2, err := intOrErr()
if err != nil {
// handle error
}
// ...
_, _ = ret, ret2 // Just so we can compile the code.
}
func nestedDoOrErr() error {
// ...
if err := doOrErr(); err != nil {
return errors.Wrap(err, "do")
}
return nil
}