-
Notifications
You must be signed in to change notification settings - Fork 0
/
recover_test.go
64 lines (57 loc) · 1.81 KB
/
recover_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
package panicgroup_test
import (
"errors"
"fmt"
"github.com/getkalido/panicgroup"
)
var ErrSomethingTerrible error = errors.New("something terrible has happened!")
// ErrorWrapping illustrates how ErrRecover can be used to recover from
// a panic and convert it into a useful error instead. This allows
// the caller of the panicking function to regain control and handle
// the panic as desired.
//
// WrapEgGoWithRecover is simply a wrapper to avoid needing to manually
// do this wrapping.
func ExampleErrRecover_errorWrapping() {
// An example function, which has a chance to panic.
panicFunc := func() (err error) {
defer func() {
// ErrRecover should recover from the panic and convert it to
// an error.
errR := panicgroup.ErrRecover(recover())
if errR != nil {
err = errR
}
}()
panic(ErrSomethingTerrible)
}
err := panicFunc()
if err == nil {
fmt.Println("No error was captured.")
} else {
fmt.Println("The panic was successfully converted into an error.")
}
// Output:
// The panic was successfully converted into an error.
}
// SimplifiedWrapping illustrates how WrapEgGoWithRecover can be used
// to recover from a panic and convert it into a useful error instead.
// This allows the caller of the panicking function to regain control
// and handle the panic as desired.
//
// This simplifies the manual process of adding panic recovery to a
// block of code.
func ExampleWrapEgGoWithRecover_simplifiedWrapping() {
// An example function, which has a chance to panic.
panicFunc := panicgroup.WrapEgGoWithRecover(func() (err error) {
panic(ErrSomethingTerrible)
})
err := panicFunc()
if err == nil {
fmt.Println("No error was captured.")
} else {
fmt.Println("The panic was successfully converted into an error.")
}
// Output:
// The panic was successfully converted into an error.
}