-
Notifications
You must be signed in to change notification settings - Fork 16
/
runtime.go
58 lines (50 loc) · 1.07 KB
/
runtime.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
package runtime
import (
"log"
"runtime"
)
var PanicHandlers = []func(interface{}){logPanic}
var (
reallyCrash = true
)
func SetReallyCrash(really bool) {
reallyCrash = really
}
func HandleCrash(additionalHandlers ...func(interface{})) {
if r := recover(); r != nil {
for _, fn := range PanicHandlers {
fn(r)
}
for _, fn := range additionalHandlers {
fn(r)
}
if reallyCrash {
// Actually proceed to panic.
panic(r)
}
}
}
func logPanic(r interface{}) {
// Same as stdlib http server code. Manually allocate stack trace buffer size
// to prevent excessively large logs
const size = 64 << 10
stacktrace := make([]byte, size)
stacktrace = stacktrace[:runtime.Stack(stacktrace, false)]
if _, ok := r.(string); ok {
log.Printf("Observed a panic: %s\n%s", r, stacktrace)
} else {
log.Printf("Observed a panic: %#v (%v)\n%s", r, r, stacktrace)
}
}
func HandleError(err error, fn func(err error)) {
if err == nil {
return
}
fn(err)
}
func HandleNil[T any](pointer *T, fn func(notNilPointer *T)) {
if pointer == nil {
return
}
fn(pointer)
}