AI智能摘要
为解决C# WebAPI项目中异常处理逻辑分散的问题,通过添加ExceptionHandlerMiddleware中间件实现统一异常处理。该中间件捕获请求中的所有异常,根据异常类型返回对应的JSON格式响应:对于CustomException返回400状态码及消息;其他异常则记录错误时间、HResult等信息,并写入日志。在Program中注册该中间件后,无需在各接口重复编写try-catch,提升了代码维护性与一致性。
— 此摘要由AI分析文章内容生成,仅供参考。
一、事情起因
最近在尝试开发WEBAPI项目,所有的异常处理都是在接口中增加try catch。这样的话如果需要修改异常处理的逻辑,就需要动很多的代码。
二、具体所作修改
1. 增加 ExceptionHandlerMiddleware 错误处理中间件
2. 在 Program 添加 ExceptionHandlerMiddleware 中间件
ExceptionHandlerMiddleware.cs内容:
public class ExceptionHandlerMiddleware
{
private readonly RequestDelegate _next;
public ExceptionHandlerMiddleware(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)
{
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)HttpStatusCode.OK;
Dictionary<string, object> result = new Dictionary<string, object>();
if (exception is CustomException ex)
{
result.Add("status", 400);
result.Add("message", ex.Message);
}
else
{
long timestampInMilliseconds = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
result.Add("status", 400);
result.Add("message", "系统错误!");
result.Add("errDate", timestampInMilliseconds);
result.Add("hResult", exception.HResult);
NLogHelper.Error($"错误时间:{timestampInMilliseconds}错误代码:{exception.HResult}", exception);
}
return context.Response.WriteAsJsonAsync(result);
}
}
Program.Main方法中增加:
app.UseMiddleware<ExceptionHandlerMiddleware>();
三、测试返回内容
修改接口内容,直接抛出一个CustomException的异常:









若您喜欢这篇内容,欢迎用TRC-USDT支持创作者
Comments 2 条评论
看不懂思密达
@尐菟姫 XD 真假?