57 lines
1.6 KiB
Go
57 lines
1.6 KiB
Go
package middleware
|
|
|
|
import (
|
|
"cloudnest/internal/pkg/errors"
|
|
"cloudnest/internal/pkg/response"
|
|
"cloudnest/internal/pkg/logger"
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// ErrorHandler creates a middleware that handles errors and panics.
|
|
// ErrorHandler 创建一个处理错误和 panic 的中间件。
|
|
//
|
|
// This middleware:
|
|
// 1. Recovers from panics and logs the error.
|
|
// 2. Handles errors stored in the Gin context after processing.
|
|
// 3. Formats consistent error responses.
|
|
//
|
|
// Returns:
|
|
// - gin.HandlerFunc: The error handling middleware handler.
|
|
//
|
|
// Note:
|
|
// - Should be added as the first middleware to catch all panics.
|
|
// - Uses the custom response package for consistent error formatting.
|
|
//
|
|
// 此中间件:
|
|
// 1. 从 panic 中恢复并记录错误。
|
|
// 2. 处理处理后存储在 Gin 上下文中的错误。
|
|
// 3. 格式化一致的错误响应。
|
|
//
|
|
// 返回值:
|
|
// - gin.HandlerFunc: 错误处理中间件处理器。
|
|
//
|
|
// 注意:
|
|
// - 应该作为第一个中间件添加以捕获所有 panic。
|
|
// - 使用自定义的 response 包进行一致的错误格式化。
|
|
func ErrorHandler() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
defer func() {
|
|
if err := recover(); err != nil {
|
|
logger.Error("panic recovered", "error", err)
|
|
response.InternalError(c, "服务器内部错误")
|
|
}
|
|
}()
|
|
|
|
c.Next()
|
|
|
|
if len(c.Errors) > 0 {
|
|
err := c.Errors.Last().Err
|
|
if appErr, ok := errors.AsAppError(err); ok {
|
|
response.Error(c, appErr.Code, appErr.Message)
|
|
} else {
|
|
logger.Error("request error", "error", err)
|
|
response.InternalError(c, err.Error())
|
|
}
|
|
}
|
|
}
|
|
} |