2023-08-31 17:32:45 +08:00

44 lines
915 B
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package exception
import (
"github.com/gin-gonic/gin"
"hospital-open-api/consts"
"log"
"net/http"
"runtime/debug"
)
// Recover
// @Description: 处理全局异常
// @return gin.HandlerFunc
func Recover() gin.HandlerFunc {
return func(c *gin.Context) {
defer func() {
if r := recover(); r != nil {
// 打印错误堆栈信息
log.Printf("panic: %v\n", r)
debug.PrintStack()
c.JSON(http.StatusInternalServerError, gin.H{
"code": consts.ServerError,
"message": errorToString(r),
"data": "",
})
// 终止后续接口调用不加的话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)
}
}