-
Notifications
You must be signed in to change notification settings - Fork 0
/
paniccatcher.go
56 lines (44 loc) · 969 Bytes
/
paniccatcher.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
package httpwaymid
import (
"fmt"
"net/http"
"runtime"
"github.com/corneldamian/httpway"
)
//will catch a panic and if the logger is set will log it, if not will panic again
func PanicCatcher(w http.ResponseWriter, r *http.Request) {
ctx := httpway.GetContext(r)
defer func() {
if rec := recover(); rec != nil {
if ctx.StatusCode() == 0 {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "Internal Server error")
if _, ok := w.(http.Flusher); ok {
println("HAHAHAHAHA FLUSHER")
}
}
if !ctx.HasLog() {
panic(rec)
}
file, line := getFileLine()
ctx.Log().Error("Panic catched on %s:%d - %s", file, line, rec)
}
}()
ctx.Next(w, r)
}
func getFileLine() (file string, line int) {
_, file, line, ok := runtime.Caller(4)
if !ok {
file = "???"
line = 0
}
short := file
for i := len(file) - 1; i > 0; i-- {
if file[i] == '/' {
short = file[i+1:]
break
}
}
file = short
return
}