全局异常捕捉

This commit is contained in:
TianJun 2021-04-28 17:18:23 +08:00
parent 3da76dc5c3
commit 80caeeb8ca
1 changed files with 38 additions and 0 deletions

View File

@ -0,0 +1,38 @@
package middleware
import (
"github.com/gin-gonic/gin"
"lingye-gin/src/config"
"net/http"
"runtime/debug"
)
func GinPanic(c *gin.Context) {
defer func() {
if r := recover(); r != nil {
// 打印错误堆栈信息
config.Logger.Printf("panic: %v\n", r)
debug.PrintStack()
// 封装通用json返回
c.JSON(http.StatusOK, gin.H{
"code": http.StatusBadRequest,
"msg": errorToString(r),
"data": nil,
})
//终止后续接口调用不加的话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)
}
}