2 Star 0 Fork 0

TeamsHub/backend-gopkg

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
mw_recover.go 2.22 KB
一键复制 编辑 原始数据 按行查看 历史
HCY 提交于 10个月前 . edit pkg
package middleware
import (
"bytes"
"fmt"
"gitee.com/wuzheng0709/backend-gopkg/infrastructure/pkg/code"
"gitee.com/wuzheng0709/backend-gopkg/infrastructure/pkg/gin/log"
"github.com/getsentry/sentry-go"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"io/ioutil"
"runtime"
)
var (
dunno = []byte("???")
centerDot = []byte("·")
dot = []byte(".")
slash = []byte("/")
)
// RecoveryMiddleware 崩溃恢复中间件
func RecoveryMiddleware() gin.HandlerFunc {
logger := zap.L()
return log.Recovery(logger, true)
}
func RecoveryMiddlewareOld() gin.HandlerFunc {
return func(c *gin.Context) {
defer func() {
if err := recover(); err != nil {
stack := stack(3)
sentry.CaptureMessage(string(stack))
log.Info(string(stack))
c.JSON(500, gin.H{"code": code.Crash_Error, "msg": "发生错误,已自动上报,正在修复中"})
c.Abort()
return
}
}()
c.Next()
}
}
// stack returns a nicely formatted stack frame, skipping skip frames.
func stack(skip int) []byte {
buf := new(bytes.Buffer)
var lines [][]byte
var lastFile string
for i := skip; ; i++ {
pc, file, line, ok := runtime.Caller(i)
if !ok {
break
}
_, err := fmt.Fprintf(buf, "%s:%d (0x%x)\n", file, line, pc)
if err != nil {
continue
}
if file != lastFile {
data, err := ioutil.ReadFile(file)
if err != nil {
continue
}
lines = bytes.Split(data, []byte{'\n'})
lastFile = file
}
_, err = fmt.Fprintf(buf, "\t%s: %s\n", function(pc), source(lines, line))
if err != nil {
continue
}
}
return buf.Bytes()
}
// source returns a space-trimmed slice of the n'th line.
func source(lines [][]byte, n int) []byte {
n-- // in stack trace, lines are 1-indexed but our array is 0-indexed
if n < 0 || n >= len(lines) {
return dunno
}
return bytes.TrimSpace(lines[n])
}
// function returns, if possible, the name of the function containing the PC.
func function(pc uintptr) []byte {
fn := runtime.FuncForPC(pc)
if fn == nil {
return dunno
}
name := []byte(fn.Name())
if lastslash := bytes.LastIndex(name, slash); lastslash >= 0 {
name = name[lastslash+1:]
}
if period := bytes.Index(name, dot); period >= 0 {
name = name[period+1:]
}
name = bytes.Replace(name, centerDot, dot, -1)
return name
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/wuzheng0709/backend-gopkg.git
git@gitee.com:wuzheng0709/backend-gopkg.git
wuzheng0709
backend-gopkg
backend-gopkg
v1.3.5

搜索帮助