【项目panic处理】

This commit is contained in:
weizhihong 2023-07-28 14:45:35 +08:00
parent 037a66d676
commit 545897562d

14
init.go
View File

@ -2,6 +2,7 @@ package main
import (
"fmt"
"net/http"
"time"
"go.uber.org/zap"
@ -30,6 +31,17 @@ func InitServer() *gin.Engine {
engine := gin.New()
engine.Use(ginzap.Ginzap(zap.L(), time.DateTime, false))
engine.Use(ginzap.RecoveryWithZap(zap.L(), true))
// gin panic 异常处理,默认处理为 engine.Use(ginzap.RecoveryWithZap(zap.L(), true))
engine.Use(ginzap.CustomRecoveryWithZap(zap.L(), true, func(c *gin.Context, e interface{}) {
switch e.(type) {
case error:
err := e.(error)
c.JSON(http.StatusInternalServerError, err.Error())
default:
c.JSON(http.StatusInternalServerError, e)
}
c.Writer.WriteHeaderNow()
c.Abort()
}))
return engine
}