.net core AOP 之 ExceptionFilter 全局的异常处理

ExceptionFilter(用于全局的异常处理)

通常程序异常处理,我们使用 try catch,如下:

       public IActionResult Index()
        {
            try
            {
                var range = Enumerable.Range(1, 3).ToArray();
                var result = range[4]; // 索引越界错误
                return View();
            }
            catch (Exception)
            {
                // 错误处理
                throw;
            }
        }

有没有一种我的程序任何地方错误都统一处理了,采集到Log或者统一转到500页面呢?

有的

新建一个 CustomerExceptionFilter ,继承 Attribute, IExceptionFilter

 public class CustomerExceptionFilter : Attribute, IExceptionFilter
    {
        private readonly IHostingEnvironment _hostingEnvironment;
        private readonly IModelMetadataProvider _modelMetadataProvider;

        public CustomerExceptionFilter(IHostingEnvironment hostingEnvironment,
            IModelMetadataProvider modelMetadataProvider)
        {
            _hostingEnvironment = hostingEnvironment;
            _modelMetadataProvider = modelMetadataProvider;
        }
        /// <summary>
        /// 发生异常进入
        /// </summary>
        /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {
            if (!context.ExceptionHandled)//如果异常没有处理
            {
                if (_hostingEnvironment.IsDevelopment())//如果是开发环境
                {
                    var result = new ViewResult { ViewName = "../Exception/Index" };
                    result.ViewData = new ViewDataDictionary(_modelMetadataProvider,
                                                                context.ModelState);
                    result.ViewData.Add("Exception", context.Exception);//传递数据
                    context.Result = result;
                }
                else
                {
                    context.Result = new JsonResult(new
                    {
                        Result = false,
                        Code = 500,
                        Message = context.Exception.Message
                    });
                }
                context.ExceptionHandled = true;//异常已处理
            }
        }
    }

回到刚刚的错误

[TypeFilter(typeof(CustomerExceptionFilter))]
        public IActionResult Index()
        {
                var range = Enumerable.Range(1, 3).ToArray();
                var result = range[4];
                return View();
        }

统一展示错误信息页

 public class ExceptionController : Controller
    {
        public IActionResult Index()
        {
            
            return View();
        }
    }

展示错误 

@{
    ViewData["Title"] = "Index";
}

<h1>Index</h1>
@ViewData["Exception"]

 

谢谢