Skip to content

Commit 300cfbe

Browse files
committed
fixing bugs in errors
1 parent d991ab0 commit 300cfbe

File tree

2 files changed

+23
-20
lines changed

2 files changed

+23
-20
lines changed

errors/main.go

+21-18
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,46 @@
11
package errors
2+
3+
import "fmt"
4+
25
/*
36
In golang it is perfectly normal for functions & methods to return an error to indicate an exception
47
which differs greatly from most languages. By convention the error should be the last item returned.
58
*/
69
func Run() {
7-
returningAnError(15)
8-
handlingAnError()
9-
recoveringIfPanics()
10+
_, _ = returningAnError(15)
11+
handlingAnError()
12+
recoveringIfPanics()
1013
}
1114

1215
type MyNewError struct {
13-
number int
16+
number int
1417
}
1518

1619
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)
1821
}
1922

2023
// An example of conditionally returning an error under some circumstance.
2124
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
2629
}
2730

2831
// How to handle an error, 'raising' if something bad happens
2932
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+
}
3437
}
3538

3639
// Panics can be 'caught' and handled using the `recover` builtin idiom
3740
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+
}()
4346
}

main.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"github.com/symonk/learning-golang/arrays"
88
"github.com/symonk/learning-golang/closures"
99
"github.com/symonk/learning-golang/constants"
10+
"github.com/symonk/learning-golang/errors"
1011
"github.com/symonk/learning-golang/forloop"
1112
"github.com/symonk/learning-golang/functions"
1213
"github.com/symonk/learning-golang/generics"
@@ -28,7 +29,6 @@ import (
2829
"github.com/symonk/learning-golang/values"
2930
"github.com/symonk/learning-golang/variables"
3031
"github.com/symonk/learning-golang/workerpools"
31-
"github.com/symonk/learning-golang/errors"
3232
)
3333

3434
func main() {
@@ -81,6 +81,6 @@ func buildMap() map[string]func() {
8181
fnMap["interfaces"] = interfaces.Run
8282
fnMap["structembedding"] = structembedding.Run
8383
fnMap["generics"] = generics.Run
84-
fnMap["errors"] - errors.Run
84+
fnMap["errors"] = errors.Run
8585
return fnMap
8686
}

0 commit comments

Comments
 (0)