-
Notifications
You must be signed in to change notification settings - Fork 1
/
recovery.go
50 lines (42 loc) · 1.03 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
package middleware
import (
"fmt"
"net/http"
"runtime"
"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 {
switch v := err.(type) {
case error:
logger.Error("%s", trace(fmt.Sprintf("%s", v)))
ctx.Error(http.StatusInternalServerError, v.Error())
case string:
logger.Error("%s", v)
ctx.Error(http.StatusInternalServerError, v)
default:
logger.Error("unknown error: %v", v)
ctx.Error(http.StatusInternalServerError, "unknown 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()
}