0 Star 0 Fork 0

shallot / Go开发工具集

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
recovery.go 1.27 KB
一键复制 编辑 原始数据 按行查看 历史
shallot 提交于 2024-02-22 08:59 . 添加路由处理库。
package router
import (
"fmt"
"net"
"os"
"runtime"
"strings"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
)
// 恢复panic的中间件
func Recovery() gin.HandlerFunc {
return func(c *gin.Context) {
defer func() {
if err := recover(); err != nil {
var brokenPipe bool
if ne, ok := err.(*net.OpError); ok {
if se, ok := ne.Err.(*os.SyscallError); ok {
if strings.Contains(strings.ToLower(se.Error()), "broken pipe") || strings.Contains(strings.ToLower(se.Error()), "connection reset by peer") {
brokenPipe = true
}
}
}
// If the connection is dead, we can't write a status to it.
stack := getStack()
logrus.WithContext(c).WithError(err.(error)).Errorf("runtime stack = \n%s", stack)
if brokenPipe {
_ = c.Error(err.(error))
c.Abort()
} else {
Failure(c, err.(error))
}
}
}()
c.Next()
}
}
func getStack() (stack string) {
ptr := make([]uintptr, 100)
length := runtime.Callers(2, ptr) // skip "runtime.Callers", "getStack"
frames := runtime.CallersFrames(ptr[:length])
for {
item, more := frames.Next()
if !more {
break
}
stack += fmt.Sprintf("%s:\n\t%s:%d (0x%x)\n", item.Function, item.File, item.Line, item.Entry)
}
stack = strings.TrimSuffix(stack, "\n")
return
}
Go
1
https://gitee.com/gxsshallot/gotool.git
git@gitee.com:gxsshallot/gotool.git
gxsshallot
gotool
Go开发工具集
2324c52c6c14

搜索帮助