File tree 2 files changed +23
-20
lines changed
2 files changed +23
-20
lines changed Original file line number Diff line number Diff line change 1
1
package errors
2
+
3
+ import "fmt"
4
+
2
5
/*
3
6
In golang it is perfectly normal for functions & methods to return an error to indicate an exception
4
7
which differs greatly from most languages. By convention the error should be the last item returned.
5
8
*/
6
9
func Run () {
7
- returningAnError (15 )
8
- handlingAnError ()
9
- recoveringIfPanics ()
10
+ _ , _ = returningAnError (15 )
11
+ handlingAnError ()
12
+ recoveringIfPanics ()
10
13
}
11
14
12
15
type MyNewError struct {
13
- number int
16
+ number int
14
17
}
15
18
16
19
func (m * MyNewError ) Error () string {
17
- return fmt .Sprintf ("%d was less than 10!" , m .number )
20
+ return fmt .Sprintf ("%d was less than 10!" , m .number )
18
21
}
19
22
20
23
// An example of conditionally returning an error under some circumstance.
21
24
func returningAnError (argument int ) (int , error ) {
22
- if argument < 10 {
23
- return argument , & MyNewError ( number : argument )
24
- }
25
- return argument , nil
25
+ if argument < 10 {
26
+ return argument , & MyNewError { number : argument }
27
+ }
28
+ return argument , nil
26
29
}
27
30
28
31
// How to handle an error, 'raising' if something bad happens
29
32
func handlingAnError () {
30
- value , err := returnAnError (100 )
31
- if err != nil {
32
- panic (err )
33
- }
33
+ _ , err := returningAnError (100 )
34
+ if err != nil {
35
+ panic (err )
36
+ }
34
37
}
35
38
36
39
// Panics can be 'caught' and handled using the `recover` builtin idiom
37
40
func recoveringIfPanics () {
38
- defer func () {
39
- if r := recover (); r != nil {
40
- fmt .Println ("Recovered from error:\n " , r )
41
- }()
42
- }
41
+ defer func () {
42
+ if r := recover (); r != nil {
43
+ fmt .Println ("Recovered from error:\n " , r )
44
+ }
45
+ }()
43
46
}
Original file line number Diff line number Diff line change 7
7
"github.com/symonk/learning-golang/arrays"
8
8
"github.com/symonk/learning-golang/closures"
9
9
"github.com/symonk/learning-golang/constants"
10
+ "github.com/symonk/learning-golang/errors"
10
11
"github.com/symonk/learning-golang/forloop"
11
12
"github.com/symonk/learning-golang/functions"
12
13
"github.com/symonk/learning-golang/generics"
@@ -28,7 +29,6 @@ import (
28
29
"github.com/symonk/learning-golang/values"
29
30
"github.com/symonk/learning-golang/variables"
30
31
"github.com/symonk/learning-golang/workerpools"
31
- "github.com/symonk/learning-golang/errors"
32
32
)
33
33
34
34
func main () {
@@ -81,6 +81,6 @@ func buildMap() map[string]func() {
81
81
fnMap ["interfaces" ] = interfaces .Run
82
82
fnMap ["structembedding" ] = structembedding .Run
83
83
fnMap ["generics" ] = generics .Run
84
- fnMap ["errors" ] - errors .Run
84
+ fnMap ["errors" ] = errors .Run
85
85
return fnMap
86
86
}
You can’t perform that action at this time.
0 commit comments