ProblemDetails异常捕获
来源:1-1 课前须知,这里有你需要了解的一切

慕莱坞5376718
2021-04-15
老师你好,这种异常该如何统一捕获输出统一json格式
写回答
1回答
-
阿莱克斯刘
2024-09-27
你好!你可以通过自定义中间件或在控制器中手动处理错误响应来实现错误信息的统一格式化。
自定义中间件
首先,创建一个自定义中间件来捕获和格式化错误响应。
ErrorHandlingMiddleware.cs
C#
public class ErrorHandlingMiddleware
{
private readonly RequestDelegate _next;
public ErrorHandlingMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private static Task HandleExceptionAsync(HttpContext context, Exception exception)
{
var code = HttpStatusCode.InternalServerError; // 500 if unexpected
var result = JsonConvert.SerializeObject(new
{
status = (int)code,
msg = "操作失败!",
data = new[]
{
new
{
errors = new Dictionary<string, string[]>
{
{ "Exception", new[] { exception.Message } }
},
type = "https://tools.ietf.org/html/rfc7231#section-6.5.1",
title = "One or more validation errors occurred.",
status = (int)code,
traceId = context.TraceIdentifier
}
}
});
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)code;
return context.Response.WriteAsync(result);
}
}00
相似问题