fix: 请求体解析失败返回 400 而非 500

ExceptionMiddleware 捕获 BadHttpRequestException(非法 JSON/编码错误/请求体过大等),
按其携带的状态码返回(通常 400),避免把客户端请求格式问题误报为服务器内部错误。
This commit is contained in:
MingNian
2026-06-21 21:15:02 +08:00
parent 13714d9ed8
commit 415c7ca082

View File

@@ -24,6 +24,15 @@ public sealed class ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionM
var result = new { code = 40001, data = (object?)null, message = vex.Message }; var result = new { code = 40001, data = (object?)null, message = vex.Message };
await context.Response.WriteAsync(JsonSerializer.Serialize(result)); await context.Response.WriteAsync(JsonSerializer.Serialize(result));
} }
catch (Microsoft.AspNetCore.Http.BadHttpRequestException ex)
{
// 请求体无法解析(非法 JSON、编码错误、请求体过大等返回其携带的状态码通常 400而不是 500
_logger.LogWarning(ex, "请求解析失败: {Path}", context.Request.Path);
context.Response.StatusCode = ex.StatusCode;
context.Response.ContentType = "application/json";
var result = new { code = 40001, data = (object?)null, message = "请求格式不正确" };
await context.Response.WriteAsync(JsonSerializer.Serialize(result));
}
catch (Exception ex) catch (Exception ex)
{ {
// 生产环境不暴露内部异常详情 // 生产环境不暴露内部异常详情