-
Notifications
You must be signed in to change notification settings - Fork 1
/
recovery.go
58 lines (49 loc) · 1.48 KB
/
recovery.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 middleware
import (
"fmt"
"net/http"
"net/http/httputil"
"runtime"
"runtime/debug"
"strings"
"github.com/go-errors/errors"
"github.com/go-zoox/zoox"
)
// Recovery is the recovery middleware
func Recovery() zoox.Middleware {
return func(ctx *zoox.Context) {
defer func() {
if err := recover(); err != nil {
// stackoverflow: https://stackoverflow.com/questions/52103182/how-to-get-the-stacktrace-of-a-panic-and-store-as-a-variable
if ctx.Debug().IsDebugMode() {
fmt.Println("stacktrace from panic: \n" + string(debug.Stack()))
}
httprequest, _ := httputil.DumpRequest(ctx.Request, false)
goErr := errors.Wrap(err, 3)
reset := string([]byte{27, 91, 48, 109})
ctx.Logger.Errorf("[Nice Recovery] panic recovered:\n\n%s%s\n\n%s%s", httprequest, goErr.Error(), goErr.Stack(), reset)
switch err.(type) {
case error:
ctx.Error(http.StatusInternalServerError, "Internal Server Error")
case string:
ctx.Error(http.StatusInternalServerError, "Internal Server Error")
default:
ctx.Error(http.StatusInternalServerError, "Internal Server Error")
}
}
}()
ctx.Next()
}
}
func trace(message string) string {
var pcs [32]uintptr
n := runtime.Callers(3, pcs[:]) // skip first 3 caller
var str strings.Builder
str.WriteString(message + "\nTraceback:")
for _, pc := range pcs[:n] {
fn := runtime.FuncForPC(pc)
file, line := fn.FileLine(pc)
str.WriteString(fmt.Sprintf("\n %s:%d", file, line))
}
return str.String()
}