fix: 请求体解析失败返回 400 而非 500
ExceptionMiddleware 捕获 BadHttpRequestException(非法 JSON/编码错误/请求体过大等), 按其携带的状态码返回(通常 400),避免把客户端请求格式问题误报为服务器内部错误。
This commit is contained in:
@@ -24,6 +24,15 @@ public sealed class ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionM
|
||||
var result = new { code = 40001, data = (object?)null, message = vex.Message };
|
||||
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)
|
||||
{
|
||||
// 生产环境不暴露内部异常详情
|
||||
|
||||
Reference in New Issue
Block a user