-
Notifications
You must be signed in to change notification settings - Fork 0
/
fns.go
95 lines (77 loc) · 2.36 KB
/
fns.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package relay
import (
"fmt"
"os"
"path"
)
// CheckFunc implementations should verify if an error is not nil.
type CheckFunc func(err error)
// CodedCheckFunc implementations should verify if an error is not nil, and
// pass through an exit code via wrapping error to final handling.
type CodedCheckFunc func(code int, err error)
// TripFunc implementations should immediately set off final handling using the
// format and optional args provided.
type TripFunc func(format string, args ...interface{})
// TripFunc implementations should immediately set off final handling using the
// format and optional args provided, and pass through an exit code via wrapping
// error.
type CodedTripFunc func(code int, format string, args ...interface{})
// TripFn wraps the provided CheckFunc so that it is a TripFunc.
func TripFn(ck CheckFunc) TripFunc {
return func(format string, args ...interface{}) {
ck(fmt.Errorf(format, args...))
}
}
// CodedTripFn wraps the provided CodedCheckFunc so that it is a CodedTripFunc.
func CodedTripFn(ck CodedCheckFunc) CodedTripFunc {
return func(code int, format string, args ...interface{}) {
ck(code, fmt.Errorf(format, args...))
}
}
// DefaultHandler returns an error handler that prints "{cmd_name}: {err_msg}"
// to stderr and then call os.Exit. If the handled error happens to satisfy the
// ExitCoder interface, that value will be used as the exit code. Otherwise, 1
// will be used.
func DefaultHandler() func(error) {
return func(err error) {
if err == nil {
return
}
cmd := path.Base(os.Args[0])
fmt.Fprintf(os.Stderr, "%s: %v\n", cmd, err)
code := 1
if ec, ok := err.(ExitCoder); ok {
code = ec.ExitCode()
}
os.Exit(code)
}
}
// Handle checks the recover() builtin and handles the error which tripped the
// relay, if any.
func Handle() {
v := recover()
if v == nil {
return
}
r, ok := v.(*Relay)
if !ok {
panic(v)
}
r.h(r.err)
}
// Fns setups a new Relay and returns both a CheckFunc and TripFunc for caller
// convenience.
func Fns(handler ...func(error)) (CheckFunc, TripFunc) {
r := New(handler...)
c := r.Check
t := TripFn(c)
return c, t
}
// CodedFns setups a new Relay and returns both a CodedCheckFunc and
// CodedTripFunc or caller convenience.
func CodedFns(handler ...func(error)) (CodedCheckFunc, CodedTripFunc) {
r := New(handler...)
c := r.CodedCheck
t := CodedTripFn(c)
return c, t
}