概念
异常过滤器是一种可以在 WebAPI 中捕获那些未得到处理的异常的过滤器,要想创建异常过滤器,你需要实现 IExceptionFilter 接口,不过这种方式比较麻烦,更快捷的方法是直接继承 ExceptionFilterAttribute 并重写里面的 OnException()
方法即可,这是因为 ExceptionFilterAttribute 类本身就实现了 IExceptionFilter 接口
全局
XXX.Common项目下新建自定义异常类:新建文件夹【Custom】新建类:BusinessException.cs【名字自己定义】
using System; namespace Test.Common.Custom { public class BusinessException : Exception { } }
WebApi项目下新建文件夹【Custom/Exception】,在Exception文件夹下新建类:CustomExceptionFilterAttribute
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Extensions.Configuration; using Test.Common.Custom; namespace Test.WebApi.Custom.Exception { public class CustomExceptionFilterAttribute : ExceptionFilterAttribute { private readonly IConfiguration _configuration; public CustomExceptionFilterAttribute(IConfiguration configuration) { _configuration = configuration; } public override void OnException(ExceptionContext context) { #region 自定义异常 if (context.Exception.GetType() == typeof(BusinessException)) { ResponseDto response = new ResponseDto() { Success = false, Message = context.Exception.Message }; context.Result = new JsonResult(response); } #endregion #region 捕获程序异常,友好提示 else { ResponseDto response = new ResponseDto() { Success = false, Message = "服务器忙,请稍后再试" }; if (_configuration["AppSetting:DisplayExceptionOrNot"] == "1") { response.Message = context.Exception.Message; } context.Result = new JsonResult(response); } #endregion } } }
Startup中注册
options.Filters.Add<CustomExceptionFilterAttribute>();
缩小粒度到 Controller 或者 Action 级别
[DatabaseExceptionFilter] public class EmployeesController : ApiController { //Some code } [CustomExceptionFilter] public IEnumerable<string> Get() { throw new DivideByZeroException(); }