Files
web_template/internal/middleware/recover.go
2026-07-10 10:06:44 +00:00

29 lines
637 B
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package middleware
import (
"log"
"net/http"
"runtime/debug"
"github.com/gin-gonic/gin"
)
// Recover panic 恢复中间件,捕获 panic 并返回 500 JSON,同时记录请求 ID 和堆栈
func Recover() gin.HandlerFunc {
return func(c *gin.Context) {
defer func() {
if r := recover(); r != nil {
rid := GetRequestID(c)
log.Printf("[ERROR] req_id=%s | panic recovered: %v\n%s", rid, r, debug.Stack())
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{
"code": 1,
"message": "服务器内部错误",
"request_id": rid,
"data": nil,
})
}
}()
c.Next()
}
}