From d9d9beed1760f467b5b007f80611f4d2975b62e1 Mon Sep 17 00:00:00 2001 From: MSuMshk <2039814060@qq.com> Date: Thu, 4 Dec 2025 22:29:13 +0800 Subject: [PATCH] =?UTF-8?q?chore:=20=E4=BC=98=E5=8C=96=E4=B8=9A=E5=8A=A1?= =?UTF-8?q?=E5=BC=82=E5=B8=B8=E7=8A=B6=E6=80=81=E7=A0=81=E9=80=8F=E4=BC=A0?= =?UTF-8?q?=E8=A7=84=E5=88=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Middleware/ExceptionHandlingMiddleware.cs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) 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,