ASP.NET CORE 学习之自定义异常处理

 为什么异常处理选择中间件?

传统的ASP.NET可以采用异常过滤器的方式处理异常,在ASP.NET CORE中,是以多个中间件连接而成的管道形式处理请求的,不过常用的五大过滤器得以保留,同样可以采用异常过滤器处理异常,但是异常过滤器不能处理MVC中间件以外的异常,为了全局统一考虑,采用中间件处理异常更为合适

 

为什么选择自定义异常中间件?

 先来看看ASP.NET CORE 内置的三个异常处理中间件 DeveloperExceptionPageMiddleware , ExceptionHandlerMiddleware, StatusCodePagesMiddleware 

1.DeveloperExceptionPageMiddleware 
 能给出详细的请求/返回/错误信息,因为包含敏感信息,所以仅适合开发环境

2.ExceptionHandlerMiddleware  (蒋神博客 

 1     /// <summary> 2     /// 异常中间件配置对象  3     /// </summary> 4     public class CustomExceptionMiddleWareOption  5     {  6         public CustomExceptionMiddleWareOption(  7             CustomExceptionHandleType handleType = CustomExceptionHandleType.JsonHandle,  8             IList<PathString> jsonHandleUrlKeys = null,  9             string errorHandingPath = "") 10         { 11             HandleType = handleType; 12             JsonHandleUrlKeys = jsonHandleUrlKeys; 13             ErrorHandingPath = errorHandingPath; 14         } 15 16         /// <summary>17         /// 异常处理方式 18         /// </summary>19         public CustomExceptionHandleType HandleType { get; set; } 20 21         /// <summary>22         /// Json处理方式的Url关键字 23         /// <para>仅HandleType=Both时生效</para>24         /// </summary>25         public IList<PathString> JsonHandleUrlKeys { get; set; } 26 27         /// <summary>28         /// 错误跳转页面 29         /// </summary>30         public PathString ErrorHandingPath { get; set; } 31     } 32 33     /// <summary>34     /// 错误处理方式 35     /// </summary>36     public enum CustomExceptionHandleType 37     { 
                        
关键字:
50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信