This repository has been archived by the owner on Mar 30, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdummy_example_test.go
77 lines (62 loc) · 1.76 KB
/
dummy_example_test.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// +build !strict
package tests_test
import (
"errors"
"fmt"
"github.com/hectorj/go-resultgen/tests"
)
//go:generate go-resultgen Dummy --tags=!strict
/*
// In the tests package, we have:
type Dummy struct {
ID int
}
*/
func Example() {
// We get a result. We don't know yet if we have an error, or a valid Dummy instance.
result := DummyGetter(true)
// So we check for an error first.
if err := result.GetError(); err != nil {
// Here is our error processing code.
// In real life you would probably use a more sensible logging strategy, or just return the error.
// The important point is that we won't call result.GetDummy() if there is an error.
fmt.Println(1, "error:", err)
return
}
// As you will see in the ouput, there is no error
fmt.Println(1, "id:", result.GetDummy().ID)
// Let's try again
result2 := DummyGetter(false)
if err := result2.GetError(); err != nil {
// As you will see in the ouput, this time we actually have an error
fmt.Println(2, "error:", err)
} else {
fmt.Println(2, "id:", result2.GetDummy().ID)
return
}
// The following examples are unsafe, they may panic.
defer func() {
if panicErr := recover(); panicErr != nil {
fmt.Println("panic:", panicErr)
}
}()
result3 := DummyGetter(true)
// No error check, YOLO
fmt.Println(3, "id:", result3.GetDummy().ID) // Does not panic because the result is valid
result4 := DummyGetter(false)
// Playing russian roulette here
fmt.Println(4, "id:", result4.GetDummy().ID) // Panics. We played, we lost.
// Output:
// 1 id: 42
// 2 error: invalid
// 3 id: 42
// panic: invalid
}
func DummyGetter(valid bool) tests.DummyResult {
if valid {
return tests.NewValidDummyResult(tests.Dummy{
ID: 42,
})
}
return tests.NewFailedDummyResult(errors.New("invalid"))
}