做完了一部分,备份一下,防止以外删除
This commit is contained in:
44
internal/middleware/recover.go
Normal file
44
internal/middleware/recover.go
Normal file
@@ -0,0 +1,44 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"runtime/debug"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"go.uber.org/zap"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/response"
|
||||
)
|
||||
|
||||
// Recover 创建自定义 panic 恢复中间件
|
||||
func Recover(logger *zap.Logger) fiber.Handler {
|
||||
return func(c *fiber.Ctx) error {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
// 获取请求 ID
|
||||
requestID := ""
|
||||
if rid := c.Locals(constants.ContextKeyRequestID); rid != nil {
|
||||
requestID = rid.(string)
|
||||
}
|
||||
|
||||
// 捕获堆栈跟踪
|
||||
stack := debug.Stack()
|
||||
|
||||
// 记录 panic 信息
|
||||
logger.Error("Panic 已恢复",
|
||||
zap.String("request_id", requestID),
|
||||
zap.String("method", c.Method()),
|
||||
zap.String("path", c.Path()),
|
||||
zap.Any("panic", r),
|
||||
zap.String("stack", string(stack)),
|
||||
)
|
||||
|
||||
// 返回统一错误响应
|
||||
_ = response.Error(c, 500, errors.CodeInternalError, errors.GetMessage(errors.CodeInternalError, "zh"))
|
||||
}
|
||||
}()
|
||||
|
||||
return c.Next()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user