.Net Core 全局捕获异常-过滤器
1、代码版本
.Net Core 版本 2.2
2、自定义异常捕获类
新建一个类 CustomerExceptionFilter.cs 继承 Microsoft.AspNetCore.Mvc.Filters.IAsyncExceptionFilter 接口
/// <summary> /// 自定义过滤器 /// </summary> public class CustomerExceptionFilter : IAsyncExceptionFilter { public Task OnExceptionAsync(ExceptionContext context) { if (context.ExceptionHandled == false) { // 定义返回数据 var result = new Core.Dto.APIResult<dynamic> { Code = Core.Dto.APIResultCode.ServerError, Msg = "服务器内部错误!啦啦啦啦啦啦啊", ErrorInfo = context.Exception.Message }; context.Result = new ContentResult { StatusCode = 200, ContentType = "application/json;charset=utf-8", Content = JsonConvert.SerializeObject(result, new JsonSerializerSettings() { //设置首字母小写 ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() }) }; } context.ExceptionHandled = true; //throw new NotImplementedException(); return Task.CompletedTask; } }
3、添加加过滤器
在Startup.cs ConfigureServices方法中追加过滤器
services.AddMvc(options => { options.Filters.Add(new Filters.CustomerExceptionFilter()); });
4、效果展示