濮阳杆衣贸易有限公司

主頁 > 知識庫 > ASP.NET MVC異常處理模塊詳解

ASP.NET MVC異常處理模塊詳解

熱門標簽:塔城代理外呼系統(tǒng) 遂寧市地圖標注app 天心智能電銷機器人 地圖定位圖標標注 地圖標注專業(yè)團隊 地圖標注的公司有哪些 代理接電話機器人如何取消 400電話辦理哪家性價比高 濮陽外呼電銷系統(tǒng)怎么樣

一、前言

  異常處理是每個系統(tǒng)必不可少的一個重要部分,它可以讓我們的程序在發(fā)生錯誤時友好地提示、記錄錯誤信息,更重要的是不破壞正常的數(shù)據(jù)和影響系統(tǒng)運行。異常處理應(yīng)該是一個橫切點,所謂橫切點就是各個部分都會使用到它,無論是分層中的哪一個層,還是具體的哪個業(yè)務(wù)邏輯模塊,所關(guān)注的都是一樣的。所以,橫切關(guān)注點我們會統(tǒng)一在一個地方進行處理。無論是MVC還是WebForm都提供了這樣實現(xiàn),讓我們可以集中處理異常。

  在MVC中,在FilterConfig中,已經(jīng)默認幫我們注冊了一個HandleErrorAttribute,這是一個過濾器,它繼承了FilterAttribute類和實現(xiàn)了IExceptionFilter接口。說到異常處理,馬上就會聯(lián)想到500錯誤頁面、記錄日志等,HandleErrorAttribute可以輕松的定制錯誤頁,默認就是Error頁面;而記錄日志我們也只需要繼承它,并替換它注冊到GlobalFilterCollection即可。關(guān)于HandleErrorAttribute很多人都知道怎么使用了,這里就不做介紹了。

  ok,開始進入主題!在MVC中處理異常,相信開始很多人都是繼承HandleErrorAttribute,然后重寫OnException方法,加入自己的邏輯,例如將異常信息寫入日志文件等。當然,這并沒有任何不妥,但良好的設(shè)計應(yīng)該是場景驅(qū)動的,是動態(tài)和可配置的。例如,在場景一種,我們希望ExceptionA顯示錯誤頁面A,而在場景二中,我們希望它顯示的是錯誤頁面B,這里的場景可能是跨項目了,也可能是在同一個系統(tǒng)的不同模塊。另外,異常也可能是分級別的,例如ExceptionA發(fā)生時,我們只需要簡單的恢復(fù)狀態(tài),程序可以繼續(xù)運行,ExceptionB發(fā)生時,我們希望將它記錄到文件或者系統(tǒng)日志,而ExceptionC發(fā)生時,是個較嚴重的錯誤,我們希望程序發(fā)生郵件或者短信通知。簡單地說,不同的場景有不同的需求,而我們的程序需要更好的面對變化。當然,繼承HandleErrorAttribute也完全可以實現(xiàn)上面所說的,只不過這里我不打算去擴展它,而是重新編寫一個模塊,并且可以與原有的HandleErrorAttribute共同使用。

二、設(shè)計及實現(xiàn)

2.1 定義配置信息

  從上面已經(jīng)可以知道我們要做的事了,針對不同的異常,我們希望可以配置它的處理程序,錯誤頁等。如下一個配置:

!--自定義異常配置-->
settingException>
 exceptions>
  !--add優(yōu)先級高于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 節(jié)點用于增加具體的異常,它的 exception 屬性是必須的,而view表示錯誤頁,handler表示具體處理程序,如果view和handler都沒有,異常將交給默認的HandleErrorAttribute處理。而group節(jié)點用于分組,例如上面的UserNameEmptyException和EmailEmptyException對應(yīng)同一個處理程序和視圖。

  程序會反射讀取這個配置信息,并創(chuàng)建相應(yīng)的對象。我們把這個配置文件放到Web.config中,保證它可以隨時改隨時生效。

2.2 異常信息包裝對象

  這里我們定義一個實體對象,對應(yīng)上面的節(jié)點。如下:

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接口

  上面我們說到,不同異??赡苄枰煌幚矸绞?。這里我們設(shè)計一個接口如下:

public interface IExceptionHandler
{
  /// summary>
  /// 異常是否處理完成
  /// /summary>
  bool HasHandled{get;set;}
 
  /// summary>
  /// 處理異常
  /// /summary>
  /// param name="ex">/param>
  void Handle(Exception ex);
}

  各種異常處理程序只要實現(xiàn)該接口即可。

2.3 實現(xiàn)IExceptionFilter

  這是必須的。如下,實現(xiàn)IExceptionFilter接口,SettingExceptionProvider會根據(jù)異常對象類型從配置信息(緩存)獲取包裝對象。

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)
    {
      //執(zhí)行Handle方法        
      config.Handler.Handle(filterContext.Exception);
      if (config.Handler.HasHandled)
      {
        //異常已處理,不需要后續(xù)操作
        filterContext.ExceptionHandled = true;
        return;
      }
    }      
    //否則,如果有定制頁面,則顯示
    if(!string.IsNullOrEmpty(config.View))
    {
      //這里還可以擴展成實現(xiàn)IView的視圖
      ViewResult view = new ViewResult();
      view.ViewName = config.View;
      filterContext.Result = view;
      filterContext.ExceptionHandled = true;
      return;
    }
    //否則將異常繼續(xù)傳遞
  }
}

2.4 讀取配置文件,創(chuàng)建異常信息包裝對象

  這部分代碼比較多,事實上,你只要知道它是在讀取web.config的自定義配置節(jié)點即可。SettingExceptionProvider用于提供容器對象。

public class SettingExceptionProvider
{
  public static DictionaryType, ExceptionConfig> Container =
    new DictionaryType, 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.CastGroupElement>())
    { 
      ExceptionConfig config = new ExceptionConfig();
      config.View = group.View;
      config.Handler = CreateHandler(group.Handler);
      foreach(var item in group.AddCollection.CastAddElement>())
      {
        Exception ex = CreateException(item.Exception);
        config.Exception = ex;
        Container[ex.GetType()] = config;
      }
    }
  }
 
  private static void InitFromAddCollection(AddCollection collection)
  {
    foreach(var item in collection.CastAddElement>())
    {
      ExceptionConfig config = new ExceptionConfig();
      config.View = item.View;
      config.Handler = CreateHandler(item.Handler);
      config.Exception = CreateException(item.Exception);
      Container[config.Exception.GetType()] = config;
    }
  }
 
  //根據(jù)完全限定名創(chuàng)建IExceptionHandler對象
  private static IExceptionHandler CreateHandler(string fullName)      
  {
    if(string.IsNullOrEmpty(fullName))
    {
      return null;
    }
    Type type = Type.GetType(fullName);
    return Activator.CreateInstance(type) as IExceptionHandler;
  }
 
  //根據(jù)完全限定名創(chuàng)建Exception對象
  private static Exception CreateException(string fullName)
  {
    if(string.IsNullOrEmpty(fullName))
    {
      return null;
    }
    Type type = Type.GetType(fullName);
    return Activator.CreateInstance(type) as Exception;
  }
}

  以下是各個配置節(jié)點的信息:

  settingExceptions節(jié)點:

/// summary>
/// settingExceptions節(jié)點
/// /summary>
public class SettingExceptionSection : ConfigurationSection
{
  [ConfigurationProperty("exceptions",IsRequired=true)]
  public ExceptionsElement Exceptions
  {
    get
    {
      return (ExceptionsElement)base["exceptions"];
    }
  }
}

  exceptions節(jié)點:

/// summary>
/// exceptions節(jié)點
/// /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節(jié)點集:

/// summary>
/// group節(jié)點集
/// /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節(jié)點:

/// summary>
/// group節(jié)點
/// /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節(jié)點集:

/// summary>
/// add節(jié)點集
/// /summary>  
public class AddCollection : ConfigurationElementCollection
{     
  /*override*/
 
  protected override ConfigurationElement CreateNewElement()
  {
    return new AddElement();
  }
 
  protected override object GetElementKey(ConfigurationElement element)
  {
    return element;
  }
}

  add節(jié)點:

/// summary>
/// add節(jié)點
/// /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,一個處理密碼錯誤異常,一個處理空異常。這里沒有實際處理代碼,具體怎么處理,應(yīng)該結(jié)合具體業(yè)務(wù)了。如:

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();
}

  可以看到,相應(yīng)的Handler會被執(zhí)行,瀏覽器也會出現(xiàn)我們配置的錯誤頁面。

四、總結(jié)

  事實上這只是一個比較簡單的例子,所以我稱它為簡單的模塊,而是用框架、庫之類的詞。當然我們可以根據(jù)實際情況對它進行擴展和優(yōu)化。微軟企業(yè)庫視乎也集成這樣的模塊,有興趣的朋友可以了解一下。

您可能感興趣的文章:
  • asp.net core MVC 全局過濾器之ExceptionFilter過濾器(1)
  • Asp.net Mvc 身份驗證、異常處理、權(quán)限驗證(攔截器)實現(xiàn)代碼
  • 詳解使用Spring MVC統(tǒng)一異常處理實戰(zhàn)
  • springboot springmvc拋出全局異常的解決方法
  • MVC異常處理詳解
  • ASP.NET MVC下基于異常處理的完整解決方案總結(jié)
  • ASP.NET mvc異常處理的方法示例介紹
  • 基于SpringMVC的全局異常處理器介紹
  • ASP.NET MVC中異常處理&自定義錯誤頁詳析
  • ASP.NET MVC中異常Exception攔截的深入理解

標簽:汕頭 婁底 本溪 麗江 重慶 宜春 河南 吉林

巨人網(wǎng)絡(luò)通訊聲明:本文標題《ASP.NET MVC異常處理模塊詳解》,本文關(guān)鍵詞  ASP.NET,MVC,異常,處理,模塊,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《ASP.NET MVC異常處理模塊詳解》相關(guān)的同類信息!
  • 本頁收集關(guān)于ASP.NET MVC異常處理模塊詳解的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章
    长垣县| 余姚市| 简阳市| 乡宁县| 东乌| 通化县| 吴堡县| 巧家县| 邛崃市| 肥西县| 淮南市| 武胜县| 温宿县| 德州市| 怀柔区| 巴塘县| 锡林浩特市| 合肥市| 襄城县| 永兴县| 十堰市| 革吉县| 陆川县| 安康市| 南乐县| 汕头市| 蛟河市| 如皋市| 永德县| 漳平市| 安图县| 高要市| 临澧县| 阿合奇县| 东莞市| 彝良县| 宜宾县| 垦利县| 麦盖提县| 阳信县| 金堂县|