加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

集成EntLib实现ASP.NET MVC的异常处理

发布时间:2020-12-16 09:04:52 所属栏目:asp.Net 来源:网络整理
导读:本篇通过自定义ASP.NET MVC的异常筛选器实现了与EntLib的EHAB(Exception Handling Application Block)的集成,使我们可以通过配置的方式来定义异常处理策略,并最终通过错误页面显示被处理过的异常信息。[源代码从这里下载] 我们知道ASP.NET MVC具有一个类

本篇通过自定义ASP.NET MVC的异常筛选器实现了与EntLib的EHAB(Exception Handling Application Block)的集成,使我们可以通过配置的方式来定义异常处理策略,并最终通过错误页面显示被处理过的异常信息。[源代码从这里下载]

我们知道ASP.NET MVC具有一个类型为HandleErrorAttribute的异常筛选器可以起到错误页面的导向作用。在这里我直接让我们自定义的异常筛选器继承它,为此我们定义了如下一个名称为ExtendedHandleErrorAttribute的类型。我们通过指定异常处理策略的配置名称来创建ExtendedHandleErrorAttribute,而属性ExceptionPolicy则表示具体的异常处理策略。在重写的OnException方法中,我们在try/catch中调用了ExceptionPolicyImpl的HandleException方法,而传入该方法的对象为需要处理的异常。捕获的异常可能是原来的异常,也可能是处理后的异常,这依赖于postHandlingAction的设置。

   1: public class ExceptionHandlingAttribute: HandleErrorAttribute
   3:     public ExceptionPolicyImpl ExceptionPolicy { get; private set; }    
   5:     public ExceptionHandlingAttribute(string exceptionPolicyName)
   7:         this.ExceptionPolicy = EnterpriseLibraryContainer.Current.GetInstance<ExceptionPolicyImpl>(exceptionPolicyName);
   9:? 
  11:     {
  13:         {
  15:         }
  17:         {
  19:             base.OnException(filterContext);
  21:     }
    
   2: @{
   4: }
   6: <p><b>Exception Type: </b>@this.Model.Exception.GetType()</p>
   1: [ExtendedHandleError("UI Policy",View = "Error")]
   3: {
   5:     {
int y = 0;
   9:         return View();
  11: }

最后来看定义的Web.config中的异常处理策略,针对抛出的DivideByZeroException异常,我们将其替换成了CalculationErrorException异常,并指定了被替换后的异常消息为”Calculation Error…”。至于PostHandlingAction属性,则被设置为ThrowNewException,意味着被处理后的异常会被抛出来。对了我们的例子来说,也就是说被替换后的CalculationErrorException会被抛出。

2: configSections>
   4:              type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration.ExceptionHandlingSettings,Microsoft.Practices.EnterpriseLibrary.ExceptionHandling"/>
   7:   exceptionHandling   8:     exceptionPolicies   9:       add ="UI Policy"  10:         exceptionTypes  11:           ="InvalidOperationException"
  13:                postHandlingAction="ThrowNewException" exceptionHandlers  15:               ="ReplaceHandler"                   
  17:                    replaceExceptionType="Artech.Web.Mvc.Extensions.CalculationException,EhabIntegration"