1 Star 0 Fork 0

xingang / gcore2

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
ExceptionMiddleware.go 1.00 KB
一键复制 编辑 原始数据 按行查看 历史
xingang 提交于 2023-02-15 14:52 . gcore2
package middlewares
import (
"gitee.com/qq358678184_admin/gcore2/exceptions"
"gitee.com/qq358678184_admin/gcore2/helper"
"gitee.com/qq358678184_admin/gcore2/logHelper"
"github.com/gin-gonic/gin"
)
func ExceptionMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
defer func() {
if r := recover(); r != nil {
//打印错误堆栈信息
//log.Printf("panic: %v\n", r)
//debug.PrintStack()
exception, ok := r.(exceptions.BusinessException)
if ok {
helper.GetHttpResponseInstance().Error(exception.Message, c)
} else {
logHelper.Error(r)
helper.GetHttpResponseInstance().Error(errorToString(r), c)
}
//终止后续接口调用,不加的话recover到异常后,还会继续执行接口里后续代码
c.Abort()
}
}()
//加载完 defer recover,继续后续接口调用
c.Next()
}
}
// recover错误,转string
func errorToString(r interface{}) string {
switch v := r.(type) {
case error:
return v.Error()
default:
return r.(string)
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/qq358678184_admin/gcore2.git
git@gitee.com:qq358678184_admin/gcore2.git
qq358678184_admin
gcore2
gcore2
a1f72da8efa7

搜索帮助

344bd9b3 5694891 D2dac590 5694891