-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors07.go
63 lines (53 loc) · 1.39 KB
/
errors07.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
58
59
60
61
62
/* Alta3 Research | RZFeeser
Handling errors within our models
- Create a type
- Wrap the initial value
- Wrap the behavior in the type
- Wrap the conditionals into the type */
package main
import (
"fmt"
"errors"
)
// create a new type
type Superdivider struct {
answer int
err error
}
// wrap the behavior
func (s *Superdivider) divide(x int) {
// wrap the conditionals (create our guard)
if s.err != nil {
return
} else if x == 0 {
s.err = errors.New("math: Sorry, you cannot div by 0.") // raise an error
return
}
// protected by our guard, we can now perform the operation
s.answer = s.answer / x
}
// this function controls the "level of abstraction" we want
// to offer our user
func divide(a, b, c int) {
// wrap the initial value
z := Superdivider{a, nil}
z.divide(b)
z.divide(c)
// determine result
if z.err != nil {
//panic(z.err)
fmt.Println(z.err)
return
}
fmt.Println(z.answer)
}
func main() {
// run divide
divide(100,2,2) // should return 25
// run divide by zero
divide(100,0,20) // this causes an error
// but our handler has us at the same spot
// run divide by zero (again)
divide(100,5,0) // we are still handling our errors, just in a highly
// abstracted way
}