/
fatal.go
67 lines (56 loc) · 1.19 KB
/
fatal.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
package cli
import (
"fmt"
"log"
"sync"
)
var (
die = log.Fatalf
mx sync.Mutex
)
// SetDie alters the package level log.Fatalf implementation,
// to be used by Die(sring, ...any).
//
// If fatalFunc is set to nil, calls to Die will issue their message
// with panic instead of log.Fatalf.
//
// This should be used for testing only.
func SetDie(fatalFunc func(string, ...any)) {
mx.Lock()
defer mx.Unlock()
die = fatalFunc
}
// Die exits the current process with some final croak.
// By default, Die is a wrapper around log.Fatalf.
//
// Use SetDie to alter this behavior (e.g. for mocking).
//
// SetDie(nil) will make Die(format, args...) equivalent to
// panic(fmt.Sprintf(format, args...)).
//
// This wraps log.Fatalf, essentially for testing purpose.
func Die(format string, args ...any) {
if die == nil {
panic(fmt.Sprintf(format, args...))
}
die(format, args...)
}
// Must panic on error
func Must(err error) {
must(err)
}
// MustOrDie dies on error.
//
// Croaks a message like log.Fatalf(msg + ": %v", err)
func MustOrDie(msg string, err error) {
if err == nil {
return
}
die(fmt.Sprintf("%s: %%v", msg), err)
}
func must(err error) {
if err == nil {
return
}
panic(err)
}