-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path21_errors.go
More file actions
72 lines (62 loc) · 1.52 KB
/
21_errors.go
File metadata and controls
72 lines (62 loc) · 1.52 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package gobyexample
import (
"errors"
"fmt"
)
func f1(arg int) (int, error) {
// By convention, errors are the last return value
// and have type `error`, a built-in interface
if arg == 42 {
return -1, errors.New("can't work with 42")
}
// a `nil` in the error position indicates that
// there was no error
return arg + 3, nil
}
// We can use custom types as `errors` by implementing
// the `Error()` method on them.
type argError struct {
arg int
prob string
}
func (e *argError) Error() string {
return fmt.Sprintf("%d - %s", e.arg, e.prob)
}
// Here we use the &argError syntax to build a new
// struct, supplying values for the two fields
// `arg` and `prob`
func f2(arg int) (int, error) {
if arg == 42 {
return -1, &argError{arg, "can't work with it"}
}
return arg + 3, nil
}
// ErrorsDemo - demonstrate error handling in Go
func ErrorsDemo() {
// call f1
for _, i := range []int{7, 42} {
// note that the use of an inline error check
// on the `if` line is a common idiom in Go
if r, e := f1(i); e != nil {
fmt.Println("f1 failed:", e)
} else {
fmt.Println("f1 worked:", r)
}
}
// call f2
for _, i := range []int{7, 42} {
if r, e := f2(i); e != nil {
fmt.Println("f2 failed:", e)
} else {
fmt.Println("f2 worked:", r)
}
}
// if you want to programatically use the data in a custom error,
// you'll need to get the error as an instance of the custom error
// type via type assertion.
_, e := f2(42)
if ae, ok := e.(*argError); ok {
fmt.Println(ae.arg)
fmt.Println(ae.prob)
}
}