-
Notifications
You must be signed in to change notification settings - Fork 0
/
recover.go
76 lines (70 loc) · 1.37 KB
/
recover.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
package util
import (
"errors"
"fmt"
"log"
"os"
"runtime/debug"
"strings"
)
func Recover() {
if r := recover(); r != nil {
s, ok := r.(string)
if ok {
LogError(errors.New(s))
return
}
err := r.(error)
LogError(err)
}
}
func RecoverAndExit() {
if r := recover(); r != nil {
s, ok := r.(string)
if ok {
LogError(errors.New(s))
return
}
err := r.(error)
LogError(err)
os.Exit(1)
}
}
var ErrorLogger = func(s string) {
log.Println(s)
}
func getStackLines(stack []byte, from int, to int) []string {
lines := strings.Split(string(stack), "\n")
if len(lines) < 2 {
return []string{}
}
return lines[from:to]
}
func GetStackLines(from int, to int) []string {
return getStackLines(debug.Stack(), from, to)
}
func LogError(err error) {
if IsErrorIgnored(err) == false {
lines := strings.Split(string(debug.Stack()), "\n")
length := len(lines)
maxLength := LoggerMaxLength*2 + 7
if length > maxLength {
length = maxLength
}
var output = make([]string, length-6)
panicid := IDGenerator()
var panicidinfo string
if panicid != "" {
panicidinfo = fmt.Sprintf("[PanicID:%s] - ", panicid)
}
output[0] = fmt.Sprintf("Panic: %s%s", panicidinfo, err.Error())
output[0] += "\n" + lines[0]
copy(output[1:], lines[7:])
ErrorLogger(strings.Join(output, "\n"))
}
}
func LogIfError(err error) {
if err != nil {
LogError(err)
}
}