2025-11-28 23:30:49 +08:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
|
|
import (
|
2025-12-02 17:40:39 +08:00
|
|
|
"fmt"
|
2025-11-28 23:30:49 +08:00
|
|
|
"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{}) {
|
2025-12-02 17:40:39 +08:00
|
|
|
// 将任意类型的panic转换为字符串
|
|
|
|
|
var errMsg string
|
|
|
|
|
switch v := recovered.(type) {
|
|
|
|
|
case string:
|
|
|
|
|
errMsg = v
|
|
|
|
|
case error:
|
|
|
|
|
errMsg = v.Error()
|
|
|
|
|
default:
|
|
|
|
|
errMsg = fmt.Sprintf("%v", v)
|
2025-11-28 23:30:49 +08:00
|
|
|
}
|
|
|
|
|
|
2025-12-02 17:40:39 +08:00
|
|
|
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())),
|
|
|
|
|
)
|
|
|
|
|
|
2025-11-28 23:30:49 +08:00
|
|
|
c.JSON(http.StatusInternalServerError, gin.H{
|
|
|
|
|
"code": 500,
|
|
|
|
|
"message": "服务器内部错误",
|
|
|
|
|
})
|
|
|
|
|
})
|
|
|
|
|
}
|