29 lines
637 B
Go
29 lines
637 B
Go
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()
|
||
}
|
||
}
|