-
Notifications
You must be signed in to change notification settings - Fork 0
/
catch.go
95 lines (86 loc) · 2.27 KB
/
catch.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
package catch
import (
"fmt"
"reflect"
)
// trivial implementation of a functionCall
type funcCall struct {
err interface{}
panicked bool
}
// encapsulate the panic prone function and notify the channel.
func encapsulate(panicProne func(), errChan chan funcCall) {
panicked := true
defer func() {
err := recover()
errChan <- funcCall{
err: err,
panicked: panicked,
}
}()
panicProne()
panicked = false
}
// Panic catches a panic prone func.
func Panic(panicProne func()) (panicked bool, recoverReturn interface{}) {
errChan := make(chan funcCall)
go encapsulate(panicProne, errChan)
ret := <-errChan
return ret.panicked, ret.err
}
// Interface returns the recovered value as an interface.
func Interface(panicProne func()) interface{} {
panicked, err := Panic(panicProne)
if err != nil {
return err
}
if panicked {
return fmt.Errorf("panic called with a nil error")
}
return nil
}
// Error returns the recovered value as error.
func Error(panicProne func()) error {
recoveredValue := Interface(panicProne)
if recoveredValue != nil {
return fmt.Errorf("%s", recoveredValue)
}
return nil
}
// CanCall checks if a function with no args can be called.
// TODO add to readme.
func CanCall(function interface{}) bool {
err := Error(func() {
value := reflect.ValueOf(function)
value.Call([]reflect.Value{})
})
return err == nil
}
// valuesToInterfaces convert reflect values to interfaces.
func valuesToInterfaces(values []reflect.Value) []interface{} {
if values == nil {
return nil
}
interfaces := make([]interface{}, len(values))
for i, value := range values {
interfaces[i] = value.Interface()
}
return interfaces
}
// SanitizeFunc converts a panic prone function to a function that returns an error.
func SanitizeFunc(panicProneFunc interface{}) func(args ...interface{}) (returnedValues []interface{}, err interface{}) {
callbackValue := reflect.ValueOf(panicProneFunc)
return func(args ...interface{}) ([]interface{}, interface{}) {
in := make([]reflect.Value, 0)
for _, arg := range args {
argValue := reflect.ValueOf(arg)
in = append(in, argValue)
}
var retValues []interface{}
err := Interface(func() {
returnedValues := callbackValue.Call(in)
retValues = valuesToInterfaces(returnedValues)
})
return retValues, err
}
}