87 lines
1.9 KiB
Go
87 lines
1.9 KiB
Go
package middleware
|
|
|
|
import (
|
|
"kra/pkg/response"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"go.uber.org/zap"
|
|
)
|
|
|
|
// 全局错误日志实例
|
|
var errorLogger *zap.Logger
|
|
|
|
// ErrorCreator 错误记录创建接口
|
|
type ErrorCreator interface {
|
|
CreateError(form, info string) error
|
|
}
|
|
|
|
// 全局错误创建器
|
|
var errorCreator ErrorCreator
|
|
|
|
// SetErrorLogger 设置错误日志
|
|
func SetErrorLogger(logger *zap.Logger) {
|
|
errorLogger = logger
|
|
}
|
|
|
|
// SetErrorCreator 设置错误创建器
|
|
func SetErrorCreator(creator ErrorCreator) {
|
|
errorCreator = creator
|
|
}
|
|
|
|
// ErrorHandler 错误处理中间件
|
|
// 用于统一处理请求过程中产生的错误
|
|
func ErrorHandler() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
c.Next()
|
|
|
|
// 处理请求过程中产生的错误
|
|
if len(c.Errors) > 0 {
|
|
for _, e := range c.Errors {
|
|
// 记录错误日志
|
|
if errorLogger != nil {
|
|
errorLogger.Error("请求错误",
|
|
zap.String("path", c.Request.URL.Path),
|
|
zap.String("method", c.Request.Method),
|
|
zap.String("error", e.Error()),
|
|
)
|
|
}
|
|
|
|
// 保存错误到数据库
|
|
if errorCreator != nil {
|
|
_ = errorCreator.CreateError(c.Request.URL.Path, e.Error())
|
|
}
|
|
}
|
|
|
|
// 如果还没有写入响应,返回错误信息
|
|
if !c.Writer.Written() {
|
|
lastErr := c.Errors.Last()
|
|
response.FailWithMessage(lastErr.Error(), c)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// ErrorResponse 错误响应结构
|
|
type ErrorResponse struct {
|
|
Code int `json:"code"`
|
|
Message string `json:"message"`
|
|
Detail string `json:"detail,omitempty"`
|
|
}
|
|
|
|
// HandleError 处理错误并返回响应
|
|
func HandleError(c *gin.Context, err error, message string) {
|
|
if errorLogger != nil {
|
|
errorLogger.Error(message,
|
|
zap.String("path", c.Request.URL.Path),
|
|
zap.Error(err),
|
|
)
|
|
}
|
|
|
|
// 保存错误到数据库
|
|
if errorCreator != nil {
|
|
_ = errorCreator.CreateError(c.Request.URL.Path, err.Error())
|
|
}
|
|
|
|
response.FailWithMessage(message, c)
|
|
}
|