-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherrors.go
63 lines (53 loc) · 1011 Bytes
/
errors.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
package main
import (
"errors"
"golang.org/x/exp/slog"
"os"
"runtime/debug"
)
var (
exitCode = 1
printStack = false
)
func RecoverAndExit() {
// Solidify exitCode
defer os.Exit(exitCode)
if r := recover(); r != nil {
if err, ok := r.(error); ok {
if ep := new(ErrPanic); errors.As(err, &ep) {
slog.Error("error", "error", ep.error)
} else if errors.Is(err, ErrLogin) && exitCode == 0 {
// Don't print stack
return
}
} else if r != nil {
slog.Error("caught panic", "recover", r)
}
if printStack {
debug.PrintStack()
}
}
}
type ErrPanic struct{ error }
func (e *ErrPanic) Error() string { return e.error.Error() }
func Check(err error) {
if err != nil {
exitCode = 1
panic(&ErrPanic{err})
}
}
func Must[T any](t T, err error) T {
Check(err)
return t
}
func Defer(fn func() error) {
if err := fn(); err != nil {
exitCode = 1
slog.Error("defer", "error", err)
}
}
var ErrLogin = errors.New("")
func Login() {
exitCode = 0
panic(ErrLogin)
}