-
Notifications
You must be signed in to change notification settings - Fork 0
/
globals.go
executable file
·73 lines (58 loc) · 1.55 KB
/
globals.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
64
65
66
67
68
69
70
71
72
73
package goerrors
import (
"fmt"
"log"
)
var (
logFatal = log.Fatal
uncatchedErrorHandler ErrorHandler = func(err IError) error {
if err != nil {
logFatal(err)
}
return nil
}
)
// MainHandler is the handler for main function used with the CheckedMain function
type MainHandler func() error
// CheckedMain should be called in the main function body.
// It assumes the uncatched error to see errors with stacktraces.
func CheckedMain(handler MainHandler) {
defer func() {
recovered := recover()
if (recovered == nil) || (uncatchedErrorHandler == nil) {
return
}
var err error
recoveredError, ok := recovered.(error)
if ok {
err = recoveredError
} else {
err = fmt.Errorf("error: %s", recovered)
}
ierr, ok := err.(IError)
if !ok {
ierr = DecorateError(err)
}
cerr := uncatchedErrorHandler(ierr)
if cerr != nil {
logFatal(cerr)
}
}()
err := handler()
if err != nil {
logFatal(err)
}
}
// SetUncatchedErrorHandler defines the handler called when an error is not catched.
// But the handled is called only if the CheckedMain function is called (indeed, the handler is called by CheckedMain).
func SetUncatchedErrorHandler(handler ErrorHandler) ErrorHandler {
oldHandler := uncatchedErrorHandler
uncatchedErrorHandler = handler
return oldHandler
}
// DiscardPanic discard a panic.
// This is an helper function that should be called with a defer instruction to blocks a panic and permits to
// continuing the excution instead of exiting the program.
func DiscardPanic() {
recover()
}