-
Notifications
You must be signed in to change notification settings - Fork 0
/
try_catch_func_test.go
92 lines (76 loc) · 1.69 KB
/
try_catch_func_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
82
83
84
85
86
87
88
89
90
91
92
package try_catch
import (
"errors"
"fmt"
"github.com/stretchr/testify/assert"
"testing"
)
func TestTryCatch(t *testing.T) {
var errFoo = errors.New("foo")
// 正常执行
err := TryCatch(func() {
t.Log("ok")
})
assert.Nil(t, err)
// 执行时发生panic
err = TryCatch(func() {
panic(errFoo)
})
assert.NotNil(t, err)
assert.ErrorIs(t, err, errFoo)
}
func TestTryCatchReturn(t *testing.T) {
var errFoo = errors.New("foo")
// 正常执行
v, err := TryCatchReturn(func() int {
return 10086
})
assert.Nil(t, err)
assert.Equal(t, 10086, v)
// 执行时发生panic
v, err = TryCatchReturn(func() int {
panic(errFoo)
})
assert.NotNil(t, err)
assert.ErrorIs(t, err, errFoo)
}
func TestTryCatchReturn2(t *testing.T) {
var errFoo = errors.New("foo")
// 正常执行
v1, v2, err := TryCatchReturn2(func() (int, string) {
return 10086, "10010"
})
assert.Nil(t, err)
assert.Equal(t, 10086, v1)
assert.Equal(t, "10010", v2)
// 执行时发生panic
v1, v2, err = TryCatchReturn2(func() (int, string) {
panic(errFoo)
})
assert.NotNil(t, err)
assert.ErrorIs(t, err, errFoo)
}
func TestTryCatchReturn3(t *testing.T) {
var errFoo = errors.New("foo")
// 正常执行
v1, v2, v3, err := TryCatchReturn3(func() (int, string, float64) {
return 10086, "10010", 3.14
})
assert.Nil(t, err)
assert.Equal(t, 10086, v1)
assert.Equal(t, "10010", v2)
assert.Equal(t, 3.14, v3)
// 执行时发生panic
v1, v2, v3, err = TryCatchReturn3(func() (int, string, float64) {
panic(errFoo)
})
assert.NotNil(t, err)
assert.ErrorIs(t, err, errFoo)
}
func TestTryCatchStringPanic(t *testing.T) {
Try(func() {
panic("string")
}).DefaultCatch(func(err error) {
fmt.Println(err)
}).Do()
}