-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheck.go
102 lines (91 loc) · 2.27 KB
/
check.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
93
94
95
96
97
98
99
100
101
102
package check
import (
"fmt"
)
// Trap executes fn and attempts to recover if fn panics.
// If fn supplied an error type when panicking, trap will cancel the panic and
// return the original error.
// If fn supplied anything other than an error to the original call to panic,
// Trap will also panic. This is done intentionally to focus the
// use of Trap as an error handling mechanism, not to replace go's native
// recover function.
// If fn does not panic, or calls panic(nil), Trap will return nil.
func Trap(fn func()) (err error) {
return TrapTx(nullDB{}, func(_ Tx) {
fn()
})
}
// TrapTx follows the same rules as Trap, but also executes fn within the
// scope of a transaction.
// The transaction is rolled back if fn panics, and is committed if fn does not
// panic.
func TrapTx(txProvider TxProvider, fn func(Tx)) (err error) {
var tx Tx
defer func() {
p := recover()
if p == nil {
err = tx.Commit()
return
}
var rollbackErr error
if tx != nil {
rollbackErr = tx.Rollback()
}
if e, ok := p.(error); ok {
err = e
if rollbackErr != nil {
err = fmt.Errorf("%v\n%v", rollbackErr, err)
}
} else {
panic(p)
}
}()
tx, err = txProvider.Begin()
if err != nil {
panic(err)
}
fn(tx)
return
}
// Bool expects a value and an error.
// If err is not nil, the function will panic.
// Otherwise the value is returned,
func Bool(b bool, err error) bool {
Err(err)
return b
}
// Int expects a value and an error.
// If err is not nil, the function will panic.
// Otherwise the value is returned,
func Int(i int, err error) int {
Err(err)
return i
}
// Float64 expects a value and an error.
// If err is not nil, the function will panic.
// Otherwise the value is returned,
func Float64(f float64, err error) float64 {
Err(err)
return f
}
// String expects a value and an error.
// If err is not nil, the function will panic.
// Otherwise the value is returned,
func String(s string, err error) string {
Err(err)
return s
}
// Iface expects a value and an error.
// If err is not nil, the function will panic.
// Otherwise the value is returned,
func Iface(i interface{}, err error) interface{} {
Err(err)
return i
}
// Err evaluates an error,
// If the error is not nil, the function will panic.
func Err(err error) {
if err != nil {
panic(err)
}
}