package middleware import ( "log/slog" "net/http" "runtime/debug" "github.com/gin-gonic/gin" "github.com/kennethcheng/fuellog-api/pkg/apperror" ) // Recover 捕获 handler 中的 panic,返回统一的 500 错误响应。 // 同时把堆栈写入日志,便于定位。 func Recover() gin.HandlerFunc { return func(c *gin.Context) { defer func() { if r := recover(); r != nil { slog.Error("panic recovered", "path", c.Request.URL.Path, "method", c.Request.Method, "panic", r, "stack", string(debug.Stack()), ) c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{ "code": apperror.CodeInternal, "message": "服务器开了小差,请稍后再试", }) } }() c.Next() } }