Files
backend/internal/middleware/recovery.go

41 lines
895 B
Go
Raw Normal View History

package middleware
import (
"fmt"
"net/http"
"runtime/debug"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
// Recovery 恢复中间件
func Recovery(logger *zap.Logger) gin.HandlerFunc {
return gin.CustomRecovery(func(c *gin.Context, recovered interface{}) {
// 将任意类型的panic转换为字符串
var errMsg string
switch v := recovered.(type) {
case string:
errMsg = v
case error:
errMsg = v.Error()
default:
errMsg = fmt.Sprintf("%v", v)
}
logger.Error("服务器恐慌",
zap.String("error", errMsg),
zap.String("path", c.Request.URL.Path),
zap.String("method", c.Request.Method),
zap.String("ip", c.ClientIP()),
zap.String("user_agent", c.GetHeader("User-Agent")),
zap.String("stack", string(debug.Stack())),
)
c.JSON(http.StatusInternalServerError, gin.H{
"code": 500,
"message": "服务器内部错误",
})
})
}