-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
48 lines (41 loc) · 1.14 KB
/
main.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
package falcon
import (
"reflect"
)
// NewErrorHandler returnes new error handler
func NewErrorHandler() *ErrorHandler {
handler := ErrorHandler{}
handler.Init()
return &handler
}
// ErrorHandler will error handle
type ErrorHandler struct {
handlers map[reflect.Type]func(error, ...interface{}) interface{}
defaultHandler func(error, ...interface{}) interface{}
}
// Init Initializes
func (errorHandler *ErrorHandler) Init() {
errorHandler.handlers = map[reflect.Type](func(error, ...interface{}) interface{}){}
}
// AddHandler adds a new error handler
func (errorHandler *ErrorHandler) AddHandler(handleFunc func(error, ...interface{}) interface{},
errTypes ...interface{}) {
if errTypes == nil {
errorHandler.defaultHandler = handleFunc
return
}
errType := reflect.TypeOf(errTypes[0])
errorHandler.handlers[errType] = handleFunc
}
// Check checks err
func (errorHandler ErrorHandler) Check(err error, data ...interface{}) interface{} {
if err == nil {
return nil
}
errType := reflect.TypeOf(err)
handler, valid := errorHandler.handlers[errType]
if !valid {
handler = errorHandler.defaultHandler
}
return handler(err, data)
}