beego 错误拦截返回json
main
文件
func main() {
//初始化数据库
models.InitDb()
//拦截错误
beego.BConfig.RecoverFunc = utils.RecoverPanic
//启动
beego.Run()
}
package utils
import (
"fmt"
"github.com/astaxie/beego"
"github.com/astaxie/beego/context"
"github.com/astaxie/beego/logs"
"runtime"
)
func RecoverPanic(ctx *context.Context) {
if err := recover(); err != nil {
var stack []string
logs.Critical("the request url is ", ctx.Input.URL())
logs.Critical("Handler crashed with error", err)
for i := 1; ; i++ {
_, file, line, ok := runtime.Caller(i)
if !ok {
break
}
logs.Critical(fmt.Sprintf("%s:%d", file, line))
stack = append(stack, fmt.Sprintln(fmt.Sprintf("%s:%d", file, line)))
}
//显示错误
data := map[string]interface{}{
"ret" : 0,
"AppError": fmt.Sprintf("%v", err),
"RequestMethod": ctx.Input.Method(),
"RequestURL": ctx.Input.URI(),
"RemoteAddr": ctx.Input.IP(),
"Stack": stack,
"BeegoVersion": beego.VERSION,
"GoVersion": runtime.Version(),
}
_ = ctx.Output.JSON(data, true, true)
if ctx.Output.Status != 0 {
ctx.ResponseWriter.WriteHeader(ctx.Output.Status)
} else {
ctx.ResponseWriter.WriteHeader(500)
}
}
}