diff --git a/src/Core/TakeoutSaaS.Shared.Web/Middleware/ExceptionHandlingMiddleware.cs b/src/Core/TakeoutSaaS.Shared.Web/Middleware/ExceptionHandlingMiddleware.cs index c52d364..8b867a4 100644 --- a/src/Core/TakeoutSaaS.Shared.Web/Middleware/ExceptionHandlingMiddleware.cs +++ b/src/Core/TakeoutSaaS.Shared.Web/Middleware/ExceptionHandlingMiddleware.cs @@ -3,6 +3,7 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System.Text.Json; using System.Text.Json.Serialization; +using System.Collections.Generic; using TakeoutSaaS.Shared.Abstractions.Constants; using TakeoutSaaS.Shared.Abstractions.Exceptions; using TakeoutSaaS.Shared.Abstractions.Results; @@ -14,6 +15,16 @@ namespace TakeoutSaaS.Shared.Web.Middleware; /// public sealed class ExceptionHandlingMiddleware(RequestDelegate next, ILogger logger, IHostEnvironment environment) { + private static readonly HashSet AllowedHttpErrorCodes = new() + { + ErrorCodes.BadRequest, + ErrorCodes.Unauthorized, + ErrorCodes.Forbidden, + ErrorCodes.NotFound, + ErrorCodes.Conflict, + ErrorCodes.ValidationFailed + }; + private static readonly JsonSerializerOptions SerializerOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, @@ -63,7 +74,10 @@ public sealed class ExceptionHandlingMiddleware(RequestDelegate next, ILogger.Error(ErrorCodes.ValidationFailed, "请求参数验证失败", validationException.Errors)), BusinessException businessException => ( - StatusCodes.Status422UnprocessableEntity, + // 1. 仅当业务错误码在白名单且位于 400-499 时透传,否则回退 400 + AllowedHttpErrorCodes.Contains(businessException.ErrorCode) && businessException.ErrorCode is >= 400 and < 500 + ? businessException.ErrorCode + : StatusCodes.Status400BadRequest, ApiResponse.Error(businessException.ErrorCode, businessException.Message)), _ => ( StatusCodes.Status500InternalServerError,