-
Notifications
You must be signed in to change notification settings - Fork 1
/
recovery.go
54 lines (45 loc) · 1.4 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
package middleware
import (
"fmt"
"net/http"
"runtime"
"runtime/debug"
"strings"
"github.com/go-zoox/logger"
"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
fmt.Println("stacktrace from panic: \n" + string(debug.Stack()))
switch v := err.(type) {
case error:
logger.Errorf("[recovery][%s %s] %s", ctx.Method, ctx.Path, (fmt.Sprintf("%s", v)))
ctx.Error(http.StatusInternalServerError, "Internal Server Error")
case string:
logger.Errorf("[recovery][%s %s] %s", ctx.Method, ctx.Path, v)
ctx.Error(http.StatusInternalServerError, "Internal Server Error")
default:
logger.Errorf("[recovery][%s %s] unknown error: %#v", ctx.Method, ctx.Path, v)
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()
}