-
Notifications
You must be signed in to change notification settings - Fork 0
/
kira_recover.go
106 lines (94 loc) · 2.55 KB
/
kira_recover.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package kira
import (
"fmt"
"runtime"
)
// ErrorFrame ...
type ErrorFrame struct {
File string `json:"file"`
Func string `json:"func"`
Line int `json:"line"`
}
// ErrorJSON ...
type ErrorJSON struct {
Message string `json:"message"`
Frames []ErrorFrame `json:"frames,omitempty"`
}
// Middleware handler.
func defaultPanic(ctx *Context, err interface{}) {
// log the error
ctx.Log().Errorf("%s", err)
// Headers
if ctx.WantsJSON() {
ctx.Response().Header().Set("Content-Type", "application/json")
} else {
ctx.Response().Header().Set("Content-Type", "text/html")
}
//ctx.Status(http.StatusInternalServerError)
// if the debug mode is enabled, add the stack to the error view
if ctx.Config().GetBool("app.debug", false) {
if ctx.WantsJSON() { // JSON
var frames []ErrorFrame
for _, frame := range getFrames(100) {
frames = append(frames, ErrorFrame{
File: frame.File,
Func: frame.Func.Name(),
Line: frame.Line,
})
}
ctx.JSON(ErrorJSON{
Message: fmt.Sprintf("%s", err),
Frames: frames,
})
} else { // HTML
if ctx.ViewExists("error/debug") {
ctx.View("errors/debug", Map{
"message": err,
"frames": getFrames(100),
})
} else {
ctx.WriteString("<p>We're sorry, but something went wrong.</p> \n\n")
ctx.WriteStringf("<p>Message: <strong>%s</strong></p>\nFrames:\n\n", err)
for _, frame := range getFrames(100) {
ctx.WriteStringf("<pre>Func: %s \nFile: %s \nLine: %d</pre>\n\n", frame.Func.Name(), frame.File, frame.Line)
}
}
}
return
}
// Normal mode
if ctx.WantsJSON() {
ctx.JSON(ErrorJSON{
Message: fmt.Sprintf("%s", err),
})
} else {
if ctx.ViewExists("errors/500") {
ctx.View("errors/500")
} else {
ctx.WriteString(`<html><head><title>Internal Server Error</title></head><body>We're sorry, but something went wrong.</body></html>`)
}
}
}
func getFrames(limit int) (framesSlice []runtime.Frame) {
// Ask runtime.Callers for up to 10 pcs, including runtime.Callers itself.
pc := make([]uintptr, limit)
// TODO: later we need to hide unnecessary callers.
n := runtime.Callers(0, pc)
if n == 0 {
// No pcs available. Stop now.
// This can happen if the first argument to runtime.Callers is large.
return
}
pc = pc[:n] // pass only valid pcs to runtime.CallersFrames
frames := runtime.CallersFrames(pc)
// Loop to get frames.
// A fixed number of pcs can expand to an indefinite number of Frames.
for {
frame, more := frames.Next()
framesSlice = append(framesSlice, frame)
if !more {
break
}
}
return framesSlice
}