diff --git a/init.go b/init.go index 9120d8e..dd5e951 100644 --- a/init.go +++ b/init.go @@ -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 }