-
Notifications
You must be signed in to change notification settings - Fork 3
/
catch.go
45 lines (35 loc) · 981 Bytes
/
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
package try
import (
"reflect"
)
func (e *Exception) Catch(f any) *Exception {
if e == nil {
return nil
}
fVal := reflect.ValueOf(f)
fType := fVal.Type()
if fType.NumIn() == 1 {
firstParamType := fType.In(0)
errorType := reflect.TypeOf(e.err)
if errorType.String() == "*errors.errorString" {
var err error
errorType = reflect.TypeOf(&err).Elem()
}
if firstParamType.AssignableTo(errorType) {
fVal.Call([]reflect.Value{reflect.ValueOf(e.err)})
}
} else if fType.NumIn() == 2 {
firstParamType := fType.In(0)
errorType := reflect.TypeOf(e.err)
secondParamType := fType.In(1)
stackTraceType := reflect.TypeOf(e.stackTrace)
if errorType.String() == "*errors.errorString" {
var err error
errorType = reflect.TypeOf(&err).Elem()
}
if firstParamType.AssignableTo(errorType) && secondParamType.ConvertibleTo(stackTraceType) {
fVal.Call([]reflect.Value{reflect.ValueOf(e.err), reflect.ValueOf(e.stackTrace)})
}
}
return e
}