chore: 优化业务异常状态码透传规则
This commit is contained in:
@@ -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;
|
||||
/// </summary>
|
||||
public sealed class ExceptionHandlingMiddleware(RequestDelegate next, ILogger<ExceptionHandlingMiddleware> logger, IHostEnvironment environment)
|
||||
{
|
||||
private static readonly HashSet<int> 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<Ex
|
||||
StatusCodes.Status422UnprocessableEntity,
|
||||
ApiResponse<object>.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<object>.Error(businessException.ErrorCode, businessException.Message)),
|
||||
_ => (
|
||||
StatusCodes.Status500InternalServerError,
|
||||
|
||||
Reference in New Issue
Block a user