Skip to content

Commit ca00ca8

Browse files
zeripathtechknowlogick
authored andcommitted
Provide better panic handling (#5902)
This PR gitea'ises the macaron.Recovery() handler meaning that in the event of panic we get proper gitea 500 pages and the stacktrace is logged with the gitea logger. Signed-off-by: Andrew Thornton <art27@cantab.net>
1 parent 0f295ab commit ca00ca8

File tree

4 files changed

+118
-2
lines changed

4 files changed

+118
-2
lines changed

modules/context/context.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ func (ctx *Context) ServerError(title string, err error) {
136136
}
137137

138138
ctx.Data["Title"] = "Internal Server Error"
139-
ctx.HTML(404, base.TplName("status/500"))
139+
ctx.HTML(http.StatusInternalServerError, base.TplName("status/500"))
140140
}
141141

142142
// NotFoundOrServerError use error check function to determine if the error

modules/context/panic.go

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
// Copyright 2013 Martini Authors
2+
// Copyright 2014 The Macaron Authors
3+
// Copyright 2019 The Gitea Authors. All rights reserved.
4+
//
5+
// Licensed under the Apache License, Version 2.0 (the "License"): you may
6+
// not use this file except in compliance with the License. You may obtain
7+
// a copy of the License at
8+
//
9+
// http://www.apache.org/licenses/LICENSE-2.0
10+
//
11+
// Unless required by applicable law or agreed to in writing, software
12+
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13+
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14+
// License for the specific language governing permissions and limitations
15+
// under the License.
16+
17+
package context
18+
19+
import (
20+
"bytes"
21+
"fmt"
22+
"io/ioutil"
23+
"runtime"
24+
25+
macaron "gopkg.in/macaron.v1"
26+
)
27+
28+
// Recovery returns a middleware that recovers from any panics and writes a 500 and a log if so.
29+
// Although similar to macaron.Recovery() the main difference is that this error will be created
30+
// with the gitea 500 page.
31+
func Recovery() macaron.Handler {
32+
return func(ctx *Context) {
33+
defer func() {
34+
if err := recover(); err != nil {
35+
combinedErr := fmt.Errorf("%s\n%s", err, string(stack(3)))
36+
ctx.ServerError("PANIC:", combinedErr)
37+
}
38+
}()
39+
40+
ctx.Next()
41+
}
42+
}
43+
44+
var (
45+
unknown = []byte("???")
46+
)
47+
48+
// Although we could just use debug.Stack(), this routine will return the source code
49+
// skip the provided number of frames - i.e. allowing us to ignore this function call
50+
// and the preceding function call.
51+
// If the problem is a lack of memory of course all this is not going to work...
52+
func stack(skip int) []byte {
53+
buf := new(bytes.Buffer)
54+
55+
// Store the last file we opened as its probable that the preceding stack frame
56+
// will be in the same file
57+
var lines [][]byte
58+
var lastFilename string
59+
for i := skip; ; i++ { // Skip over frames
60+
programCounter, filename, lineNumber, ok := runtime.Caller(i)
61+
// If we can't retrieve the information break - basically we're into go internals at this point.
62+
if !ok {
63+
break
64+
}
65+
66+
// Print equivalent of debug.Stack()
67+
fmt.Fprintf(buf, "%s:%d (0x%x)\n", filename, lineNumber, programCounter)
68+
// Now try to print the offending line
69+
if filename != lastFilename {
70+
data, err := ioutil.ReadFile(filename)
71+
if err != nil {
72+
// can't read this sourcefile
73+
// likely we don't have the sourcecode available
74+
continue
75+
}
76+
lines = bytes.Split(data, []byte{'\n'})
77+
lastFilename = filename
78+
}
79+
fmt.Fprintf(buf, "\t%s: %s\n", functionName(programCounter), source(lines, lineNumber))
80+
}
81+
return buf.Bytes()
82+
}
83+
84+
// functionName converts the provided programCounter into a function name
85+
func functionName(programCounter uintptr) []byte {
86+
function := runtime.FuncForPC(programCounter)
87+
if function == nil {
88+
return unknown
89+
}
90+
name := []byte(function.Name())
91+
92+
// Because we provide the filename we can drop the preceding package name.
93+
if lastslash := bytes.LastIndex(name, []byte("/")); lastslash >= 0 {
94+
name = name[lastslash+1:]
95+
}
96+
// And the current package name.
97+
if period := bytes.Index(name, []byte(".")); period >= 0 {
98+
name = name[period+1:]
99+
}
100+
// And we should just replace the interpunct with a dot
101+
name = bytes.Replace(name, []byte("·"), []byte("."), -1)
102+
return name
103+
}
104+
105+
// source returns a space-trimmed slice of the n'th line.
106+
func source(lines [][]byte, n int) []byte {
107+
n-- // in stack trace, lines are 1-indexed but our array is 0-indexed
108+
if n < 0 || n >= len(lines) {
109+
return unknown
110+
}
111+
return bytes.TrimSpace(lines[n])
112+
}

routers/routes/routes.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,9 @@ func NewMacaron() *macaron.Macaron {
136136
DisableDebug: !setting.EnablePprof,
137137
}))
138138
m.Use(context.Contexter())
139+
// OK we are now set-up enough to allow us to create a nicer recovery than
140+
// the default macaron recovery
141+
m.Use(context.Recovery())
139142
m.SetAutoHead(true)
140143
return m
141144
}

templates/status/500.tmpl

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@
33
<p style="margin-top: 100px"><img src="{{AppSubUrl}}/img/500.png" alt="500"/></p>
44
<div class="ui divider"></div>
55
<br>
6-
{{if .ErrorMsg}}<p>An error has occurred : {{.ErrorMsg}}</p>{{end}}
6+
{{if .ErrorMsg}}<p>An error has occurred :</p>
7+
<pre style="text-align: left">{{.ErrorMsg}}</pre>{{end}}
78
{{if .ShowFooterVersion}}<p>Application Version: {{AppVer}}</p>{{end}}
89
{{if .IsAdmin}}<p>If you are sure this is Gitea bug, please search for issue on <a href="https://github.com/go-gitea/gitea/issues">GitHub</a> and open new issue if necessary.</p>{{end}}
910
</div>

0 commit comments

Comments
 (0)