NetCore 全局异常过滤器
第一步:创建过滤器
/// <summary> /// 全局异常过滤器 /// 调用示例:throw new NotImplementedException(); /// </summary> public class GlobalExceptionFilter : IExceptionFilter { readonly IWebHostEnvironment hostEnvironment; public GlobalExceptionFilter(IWebHostEnvironment _hostEnvironment) { this.hostEnvironment = _hostEnvironment; } public void OnException(ExceptionContext context) { if (!context.ExceptionHandled)//如果异常没有处理 { var result = ResponseMessage.Error("服务器发生未处理的异常"); if (hostEnvironment.IsDevelopment()) { result.Message += "," + context.Exception.Message; result.Data = context.Exception.StackTrace; } context.Result = new JsonResult(result); context.ExceptionHandled = true;//异常已处理 } } }
第二步:配置过滤器
builder.Services.AddControllers(option => { option.Filters.Add<GlobalExceptionFilter>(); } );
第四步:异常示例
[HttpGet("{id}")] public ActionResult Get(int id) { throw new NotImplementedException(); }
第五步:运行结果