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

2019-05-22 21:38:41王旭

  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)
  {
    //具体处理逻辑...
  }
}