当前位置: 移动技术网 > IT编程>开发语言>.net > ASP.NET MVC异常处理模块详解

ASP.NET MVC异常处理模块详解

2017年12月12日  | 移动技术网IT编程  | 我要评论
一、前言   异常处理是每个系统必不可少的一个重要部分,它可以让我们的程序在发生错误时友好地提示、记录错误信息,更重要的是不破坏正常的数据和影响系统运行。异常处理应该是一

一、前言

  异常处理是每个系统必不可少的一个重要部分,它可以让我们的程序在发生错误时友好地提示、记录错误信息,更重要的是不破坏正常的数据和影响系统运行。异常处理应该是一个横切点,所谓横切点就是各个部分都会使用到它,无论是分层中的哪一个层,还是具体的哪个业务逻辑模块,所关注的都是一样的。所以,横切关注点我们会统一在一个地方进行处理。无论是mvc还是webform都提供了这样实现,让我们可以集中处理异常。

  在mvc中,在filterconfig中,已经默认帮我们注册了一个handleerrorattribute,这是一个过滤器,它继承了filterattribute类和实现了iexceptionfilter接口。说到异常处理,马上就会联想到500错误页面、记录日志等,handleerrorattribute可以轻松的定制错误页,默认就是error页面;而记录日志我们也只需要继承它,并替换它注册到globalfiltercollection即可。关于handleerrorattribute很多人都知道怎么使用了,这里就不做介绍了。

  ok,开始进入主题!在mvc中处理异常,相信开始很多人都是继承handleerrorattribute,然后重写onexception方法,加入自己的逻辑,例如将异常信息写入日志文件等。当然,这并没有任何不妥,但良好的设计应该是场景驱动的,是动态和可配置的。例如,在场景一种,我们希望exceptiona显示错误页面a,而在场景二中,我们希望它显示的是错误页面b,这里的场景可能是跨项目了,也可能是在同一个系统的不同模块。另外,异常也可能是分级别的,例如exceptiona发生时,我们只需要简单的恢复状态,程序可以继续运行,exceptionb发生时,我们希望将它记录到文件或者系统日志,而exceptionc发生时,是个较严重的错误,我们希望程序发生邮件或者短信通知。简单地说,不同的场景有不同的需求,而我们的程序需要更好的面对变化。当然,继承handleerrorattribute也完全可以实现上面所说的,只不过这里我不打算去扩展它,而是重新编写一个模块,并且可以与原有的handleerrorattribute共同使用。

二、设计及实现

2.1 定义配置信息

  从上面已经可以知道我们要做的事了,针对不同的异常,我们希望可以配置它的处理程序,错误页等。如下一个配置:

<!--自定义异常配置-->
<settingexception>
 <exceptions>
  <!--add优先级高于group-->
  <add exception="exceptions.passworderrorexception"
     view ="passworderrorview"
     handler="exceptionhandlers.passworderrorexceptionhandler"/>
  <groups>
   <!--group可以配置一种异常的view和handler-->
   <group view="emptyerrorview" handler="exceptionhandlers.emptyexceptionhandler">
    <add exception="exceptions.usernameemptyexception"/>
    <add exception="exceptions.emailemptyexception"/>
   </group>    
  </groups>
 </exceptions>
</settingexception>

  其中,add 节点用于增加具体的异常,它的 exception 属性是必须的,而view表示错误页,handler表示具体处理程序,如果view和handler都没有,异常将交给默认的handleerrorattribute处理。而group节点用于分组,例如上面的usernameemptyexception和emailemptyexception对应同一个处理程序和视图。

  程序会反射读取这个配置信息,并创建相应的对象。我们把这个配置文件放到web.config中,保证它可以随时改随时生效。

2.2 异常信息包装对象

  这里我们定义一个实体对象,对应上面的节点。如下:

public class exceptionconfig
{
  /// <summary>
  /// 视图
  /// </summary>
  public string view{get;set;}
 
  /// <summary>
  /// 异常对象
  /// </summary>
  public exception exception{get;set;}
 
  /// <summary>
  /// 异常处理程序
  /// </summary>
  public iexceptionhandler handler{get;set;}
}

2.3 定义handler接口

  上面我们说到,不同异常可能需要不同处理方式。这里我们设计一个接口如下:

public interface iexceptionhandler
{
  /// <summary>
  /// 异常是否处理完成
  /// </summary>
  bool hashandled{get;set;}
 
  /// <summary>
  /// 处理异常
  /// </summary>
  /// <param name="ex"></param>
  void handle(exception ex);
}

  各种异常处理程序只要实现该接口即可。

2.3 实现iexceptionfilter

  这是必须的。如下,实现iexceptionfilter接口,settingexceptionprovider会根据异常对象类型从配置信息(缓存)获取包装对象。

public class settinghandleerrorfilter : iexceptionfilter
{
  public void onexception(exceptioncontext filtercontext)
  {
    if(filtercontext == null)
    {
      throw new argumentnullexception("filtercontext");
    }
    exceptionconfig config = settingexceptionprovider.container[filtercontext.exception.gettype()];
    if(config == null)
    {
      return;
    }
    if(config.handler != null)
    {
      //执行handle方法        
      config.handler.handle(filtercontext.exception);
      if (config.handler.hashandled)
      {
        //异常已处理,不需要后续操作
        filtercontext.exceptionhandled = true;
        return;
      }
    }      
    //否则,如果有定制页面,则显示
    if(!string.isnullorempty(config.view))
    {
      //这里还可以扩展成实现iview的视图
      viewresult view = new viewresult();
      view.viewname = config.view;
      filtercontext.result = view;
      filtercontext.exceptionhandled = true;
      return;
    }
    //否则将异常继续传递
  }
}

2.4 读取配置文件,创建异常信息包装对象

  这部分代码比较多,事实上,你只要知道它是在读取web.config的自定义配置节点即可。settingexceptionprovider用于提供容器对象。

public class settingexceptionprovider
{
  public static dictionary<type, exceptionconfig> container =
    new dictionary<type, exceptionconfig>();
 
  static settingexceptionprovider()
  {
    initcontainer();
  }
 
  //读取配置信息,初始化容器
  private static void initcontainer()
  {
    var section = webconfigurationmanager.getsection("settingexception") as settingexceptionsection;
    if(section == null)
    {
      return;
    }
    initfromgroups(section.exceptions.groups);
    initfromaddcollection(section.exceptions.addcollection);
  }
 
  private static void initfromgroups(groupcollection groups)
  {           
    foreach (var group in groups.cast<groupelement>())
    { 
      exceptionconfig config = new exceptionconfig();
      config.view = group.view;
      config.handler = createhandler(group.handler);
      foreach(var item in group.addcollection.cast<addelement>())
      {
        exception ex = createexception(item.exception);
        config.exception = ex;
        container[ex.gettype()] = config;
      }
    }
  }
 
  private static void initfromaddcollection(addcollection collection)
  {
    foreach(var item in collection.cast<addelement>())
    {
      exceptionconfig config = new exceptionconfig();
      config.view = item.view;
      config.handler = createhandler(item.handler);
      config.exception = createexception(item.exception);
      container[config.exception.gettype()] = config;
    }
  }
 
  //根据完全限定名创建iexceptionhandler对象
  private static iexceptionhandler createhandler(string fullname)      
  {
    if(string.isnullorempty(fullname))
    {
      return null;
    }
    type type = type.gettype(fullname);
    return activator.createinstance(type) as iexceptionhandler;
  }
 
  //根据完全限定名创建exception对象
  private static exception createexception(string fullname)
  {
    if(string.isnullorempty(fullname))
    {
      return null;
    }
    type type = type.gettype(fullname);
    return activator.createinstance(type) as exception;
  }
}

  以下是各个配置节点的信息:

  settingexceptions节点:

/// <summary>
/// settingexceptions节点
/// </summary>
public class settingexceptionsection : configurationsection
{
  [configurationproperty("exceptions",isrequired=true)]
  public exceptionselement exceptions
  {
    get
    {
      return (exceptionselement)base["exceptions"];
    }
  }
}

  exceptions节点:

/// <summary>
/// exceptions节点
/// </summary>
public class exceptionselement : configurationelement
{
  private static readonly configurationproperty _addproperty =
    new configurationproperty("", typeof(addcollection), null, configurationpropertyoptions.isdefaultcollection);
 
  [configurationproperty("", isdefaultcollection = true)]
  public addcollection addcollection
  {
    get
    {
      return (addcollection)base[_addproperty];
    }
  }
 
  [configurationproperty("groups")]
  public groupcollection groups
  {
    get
    {
      return (groupcollection)base["groups"];
    }
  }
}

  group节点集:

/// <summary>
/// group节点集
/// </summary>
[configurationcollection(typeof(groupelement),additemname="group")]
public class groupcollection : configurationelementcollection
{   
  /*override*/
 
  protected override configurationelement createnewelement()
  {
    return new groupelement();
  }
 
  protected override object getelementkey(configurationelement element)
  {
    return element;
  }
}

  group节点:

/// <summary>
/// group节点
/// </summary>
public class groupelement : configurationelement
{
  private static readonly configurationproperty _addproperty =
    new configurationproperty("", typeof(addcollection), null, configurationpropertyoptions.isdefaultcollection);
 
  [configurationproperty("view")]
  public string view
  {
    get
    {
      return base["view"].tostring();
    }
  }
 
  [configurationproperty("handler")]
  public string handler
  {
    get
    {
      return base["handler"].tostring();
    }
  }
 
  [configurationproperty("", isdefaultcollection = true)]
  public addcollection addcollection
  {
    get
    {
      return (addcollection)base[_addproperty];
    }
  }    
}

  add节点集:

/// <summary>
/// add节点集
/// </summary>  
public class addcollection : configurationelementcollection
{     
  /*override*/
 
  protected override configurationelement createnewelement()
  {
    return new addelement();
  }
 
  protected override object getelementkey(configurationelement element)
  {
    return element;
  }
}

  add节点:

/// <summary>
/// add节点
/// </summary>
public class addelement : configurationelement
{
  [configurationproperty("view")]
  public string view
  {
    get
    {
      return base["view"] as string;
    }
  }
 
  [configurationproperty("handler")]
  public string handler
  {
    get
    {
      return base["handler"] as string;
    }
  }
 
  [configurationproperty("exception", isrequired = true)]
  public string exception
  {
    get
    {
      return base["exception"] as string;
    }
  }
}

三、测试

  ok,下面测试一下,首先要在filterconfig的registerglobalfilters方法中在,handlererrorattribute前注册我们的过滤器:

  filters.add(new settinghandleerrorfilter())。

3.1 准备异常对象

   准备几个简单的异常对象:

public class passworderrorexception : exception{}
public class usernameemptyexception : exception{}
public class emailemptyexception : exception{}

3.2 准备handler

  针对上面的异常,我们准备两个handler,一个处理密码错误异常,一个处理空异常。这里没有实际处理代码,具体怎么处理,应该结合具体业务了。如:

public class passworderrorexceptionhandler : iexceptionhandler
{
  public bool hashandled{get;set;}
   
  public void handle(exception ex)
  {
    //具体处理逻辑...
  }
}
 
public class emptyexceptionhandler : iexceptionhandler
{
  public bool hashandled { get; set; }
 
  public void handle(exception ex)
  {
    //具体处理逻辑...
  }
}

3.3 抛出异常

  按照上面的配置,我们在action中手动throw异常

public actionresult index()
{
  throw new passworderrorexception();
}
public actionresult index2()
{
  throw new usernameemptyexception();
}
public actionresult index3()
{
  throw new emailemptyexception();
}

  可以看到,相应的handler会被执行,浏览器也会出现我们配置的错误页面。

四、总结

  事实上这只是一个比较简单的例子,所以我称它为简单的模块,而是用框架、库之类的词。当然我们可以根据实际情况对它进行扩展和优化。微软企业库视乎也集成这样的模块,有兴趣的朋友可以了解一下。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网