package middleware import ( "net/http" "github.com/gin-gonic/gin" "ai_scheduler/internal/data/error" ) // ErrorHandler 是一个处理应用错误的中间件 func ErrorHandler() gin.HandlerFunc { return func(c *gin.Context) { // 处理请求 c.Next() // 检查是否有错误 if len(c.Errors) > 0 { // 获取最后一个错误 err := c.Errors.Last().Err // 检查是否为应用错误 if appErr, ok := errors.IsAppError(err); ok { // 返回应用错误 c.JSON(appErr.Code(), gin.H{ "status": "error", "error": gin.H{ "code": appErr.Code(), "message": appErr.Error(), }, }) return } // 处理其他类型的错误 c.JSON(http.StatusInternalServerError, gin.H{ "status": "error", "error": gin.H{ "code": http.StatusInternalServerError, "message": "Internal server error", }, }) } } }