Repository navigation
Expand file tree
/
Copy pathnice.go
More file actions
79 lines (71 loc) · 2.13 KB
/
Copy pathnice.go
File metadata and controls
79 lines (71 loc) · 2.13 KB
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
/*
Package nice provides the throw and catch error handling pattern using panic and recover.
*/
package nice
import (
"reflect"
"slices"
)
// Handler for the given artefact and error types
type Handler struct {
artefactTypes []reflect.Type
errorTypes []error
}
// With takes a handle function from parameter
// and call the function while panic artfact type matches.
// The handle func does not catch panic from other level's goroutine.
func (h Handler) With(handle func(artefact any)) {
if lastMsg := recover(); lastMsg != nil {
switch asserted := lastMsg.(type) {
case error:
typeOfError := reflect.TypeFor[error]()
// Handle general error registered
if slices.Contains(h.artefactTypes, typeOfError) {
handle(lastMsg)
return
}
// Handle specific error registered
if slices.Contains(h.errorTypes, asserted) {
handle(lastMsg)
return
}
default:
typeOfLastMsg := reflect.TypeOf(lastMsg)
if slices.Contains(h.artefactTypes, typeOfLastMsg) {
handle(lastMsg)
return
}
}
// Fallthrough if not tackled
panic(lastMsg) // This will ruin the call stack. Need a new solution.
}
}
// Tackle panic with provided targets type
// returns a Handler, which shall be pairly used With().
// Pass exact error to the `targets`,
// if you want to handle particular type of error.
// Passsing `reflect.TypeFor[error]()` registers all types of error
// to be handled by the handle function.
// Not passing any parameter to targets will assume generic error
// would be handled.
func Tackle(targets ...any) Handler {
artefactTypes := make([]reflect.Type, 0)
errorTypes := make([]error, 0)
if len(targets) == 0 {
return Handler{
artefactTypes: []reflect.Type{reflect.TypeFor[error]()},
errorTypes: errorTypes,
}
}
for _, t := range targets {
if errorType, matched := t.(error); matched {
errorTypes = append(errorTypes, errorType)
continue
}
if artefactType, matched := t.(reflect.Type); matched {
artefactTypes = append(artefactTypes, artefactType)
}
// Unknown target is being ignored and is being discarded
}
return Handler{artefactTypes: artefactTypes, errorTypes: errorTypes}
}