-
Notifications
You must be signed in to change notification settings - Fork 13
/
exception.go
48 lines (42 loc) · 1002 Bytes
/
exception.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 exception
import (
"fmt"
"runtime/debug"
"strings"
)
// Block - defines the try, catch and finally code blocks
type Block struct {
Try func()
Catch func(error)
Finally func()
}
// Throw - raises the error
// Raises the panic error
func Throw(err error) {
panic(err)
}
// Do - Executes the Exception block.
// 1. Defers the finally method, so that it can be called last
// 2. Defers the execution of catch, to recover from panic raised by Throw and callback Catch method
// 3. Executes the try method, that may raise error by calling Throw method
func (block Block) Do() {
if block.Try == nil {
return
}
if block.Finally != nil {
defer block.Finally()
}
if block.Catch != nil {
defer func() {
if obj := recover(); obj != nil {
err := obj.(error)
if strings.Contains(err.Error(), "nil pointer dereference") {
block.Catch(fmt.Errorf(err.Error() + ": \n " + string(debug.Stack())))
} else {
block.Catch(err)
}
}
}()
}
block.Try()
}