-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathrecover_test.go
81 lines (75 loc) · 1.75 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package grace
import (
"bytes"
"fmt"
"log"
"strings"
"testing"
)
func TestRecover(t *testing.T) {
var buf bytes.Buffer
log.SetOutput(&buf)
err := func() (e error) {
defer Recover(&e)
numbers := []int{1, 2}
fmt.Println(numbers[3])
return e
}()
length := len(strings.Split(strings.TrimSuffix(err.Error(), "\n"), "\n"))
if err == nil || length <= 1 {
t.Fatal("Unexpected error")
}
// add a custom function
err = func() (e error) {
e = Handler(e).Add(func(e error) error {
log.Println(e)
return e
})
defer Recover(&e)
numbers := []int{1, 2}
fmt.Println(numbers[3])
return
}()
length = len(strings.Split(strings.TrimSuffix(err.Error(), "\n"), "\n"))
if err == nil || length <= 1 || len(buf.Bytes()) <= 0 {
t.Fatal("Unexpected error", length, len(buf.Bytes()))
}
}
func TestRecovery_Error(t *testing.T) {
var buf bytes.Buffer
log.SetOutput(&buf)
// get only error message
err := func() (e error) {
e = Handler(e).Add(func(e error) error {
log.Println(e)
return e
})
defer Recover(&e).Error()
numbers := []int{1, 2}
fmt.Println(numbers[3])
return
}()
length := len(strings.Split(strings.TrimSuffix(err.Error(), "\n"), "\n"))
if err == nil || length != 1 || len(buf.Bytes()) <= 0 {
t.Fatal("Unexpected error", err, length)
}
}
func TestRecovery_Stack(t *testing.T) {
var buf bytes.Buffer
log.SetOutput(&buf)
// get only error message
err := func() (e error) {
e = Handler(e).Add(func(e error) error {
log.Println(e)
return e
})
defer Recover(&e).Stack()
numbers := []int{1, 2}
fmt.Println(numbers[3])
return
}()
length := len(strings.Split(strings.TrimSuffix(err.Error(), "\n"), "\n"))
if err == nil || length <= 1 || len(buf.Bytes()) <= 0 {
t.Fatal("Unexpected error", err, length)
}
}