Add internal/middleware/recover.go
This commit is contained in:
28
internal/middleware/recover.go
Normal file
28
internal/middleware/recover.go
Normal 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()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user