Add internal/middleware/recover.go

This commit is contained in:
ata
2026-07-10 10:06:44 +00:00
committed by Gitee
parent 5eaf457e51
commit 22f4fac069

View File

@@ -0,0 +1,28 @@
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()
}
}