一、事情起因
最近在尝试开发WEBAPI项目,所有的异常处理都是在接口中增加try catch。这样的话如果需要修改异常处理的逻辑,就需要动很多的代码。
二、具体所作修改
- 增加 ExceptionHandlerMiddleware 错误处理中间件
- 在 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的异常:
返回结果为:
若抛出 Exception 的异常:
则返回: