File tree Expand file tree Collapse file tree
internal/exercises/solutions/26_errors Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package errors
2+
3+ import (
4+ "fmt"
5+ "os"
6+ )
7+
8+ // divZeroErr is a minimal error type whose message is "division by zero".
9+ type divZeroErr struct {}
10+
11+ // Error makes divZeroErr implement error.
12+ func (divZeroErr ) Error () string { return "division by zero" }
13+
14+ // Is allows errors.Is(err, errors.New("division by zero")) to succeed.
15+ func (divZeroErr ) Is (target error ) bool {
16+ if target == nil {
17+ return false
18+ }
19+ return target .Error () == "division by zero"
20+ }
21+
22+ // divide returns a/b or a "division by zero" error when b == 0.
23+ func divide (a , b int ) (int , error ) {
24+ if b == 0 {
25+ return 0 , divZeroErr {}
26+ }
27+ return a / b , nil
28+ }
29+
30+ // processDivision prints the result or the error to stdout.
31+ func processDivision (a , b int ) {
32+ res , err := divide (a , b )
33+ if err != nil {
34+ fmt .Fprint (os .Stdout , "Error: " , err , "\n " )
35+ return
36+ }
37+ fmt .Fprint (os .Stdout , "Result: " , res , "\n " )
38+ }
You can’t perform that action at this time.
0 commit comments