-
Notifications
You must be signed in to change notification settings - Fork 36
/
recover_handler.go
59 lines (49 loc) · 1.29 KB
/
recover_handler.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
package think
import (
"fmt"
"github.com/forgoer/thinkgo/context"
"net/http/httputil"
"runtime"
"strings"
)
type RecoverHandler struct {
app *Application
}
// NewRecoverHandler The default NewRecoverHandler
func NewRecoverHandler(app *Application) Handler {
return &RecoverHandler{
app: app,
}
}
// Process Process the request to a router and return the response.
func (h *RecoverHandler) Process(req *context.Request, next Closure) (result interface{}) {
defer func() {
if err := recover(); err != nil {
var stacktrace string
for i := 1; ; i++ {
_, f, l, got := runtime.Caller(i)
if !got {
break
}
stacktrace += fmt.Sprintf("%s:%d\n", f, l)
}
httpRequest, _ := httputil.DumpRequest(req.Request, false)
headers := strings.Split(string(httpRequest), "\r\n")
for idx, header := range headers {
current := strings.Split(header, ":")
if current[0] == "Authorization" {
headers[idx] = current[0] + ": *"
}
}
logMessage := fmt.Sprintf("Recovered at Request: %s\n", strings.Join(headers, "\r\n"))
logMessage += fmt.Sprintf("Trace: %s\n", err)
logMessage += fmt.Sprintf("\n%s", stacktrace)
response := context.ErrorResponse()
if h.app.Debug {
response.SetContent(logMessage)
}
result = response
}
}()
return next(req)
}