forked from ilibs/gosql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhook.go
63 lines (55 loc) · 1.13 KB
/
hook.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
package gosql
import (
"errors"
"log"
"reflect"
"strings"
)
type Hook struct {
db *DB
Errs []error
}
func NewHook(db *DB) *Hook {
return &Hook{
db: db,
}
}
func (h *Hook) callMethod(methodName string, reflectValue reflect.Value) {
// Only get address from non-pointer
if reflectValue.CanAddr() && reflectValue.Kind() != reflect.Ptr {
reflectValue = reflectValue.Addr()
}
if methodValue := reflectValue.MethodByName(methodName); methodValue.IsValid() {
switch method := methodValue.Interface().(type) {
case func():
method()
case func() error:
h.Err(method())
case func(db *DB):
method(h.db)
case func(db *DB) error:
h.Err(method(h.db))
default:
log.Panicf("unsupported function %v", methodName)
}
}
}
// Err add error
func (h *Hook) Err(err error) error {
if err != nil {
h.Errs = append(h.Errs, err)
}
return err
}
// HasError has errors
func (h *Hook) HasError() int {
return len(h.Errs)
}
// Error format happened errors
func (h *Hook) Error() error {
var errs = make([]string, 0)
for _, e := range h.Errs {
errs = append(errs, e.Error())
}
return errors.New(strings.Join(errs, "; "))
}