235 字
1 分钟
C# WEBAPI 统一异常处理
一、事情起因
最近在尝试开发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支持创作者
TN3pU88pu1bkUgpyBuJCG1riZecFFkpe8E
请选择TRC20协议转账,感谢您的支持 ❤️
扫描二维码转账




