<dfn id="w48us"></dfn><ul id="w48us"></ul>
  • <ul id="w48us"></ul>
  • <del id="w48us"></del>
    <ul id="w48us"></ul>
  • ASP.NET MVC異常處理模塊簡單教程-ASP.NET教程實例

    時間:2024-07-19 03:52:40 ASP 我要投稿
    • 相關推薦

    ASP.NET MVC異常處理模塊簡單教程-ASP.NET教程實例推薦

      異常處理是每個系統必不可少的一個重要部分,它可以讓我們的程序在發生錯誤時友好地提示、記錄錯誤信息,更重要的是不破壞正常的數據和影響系統運行。

      在MVC中處理異常,相信開始很多人都是繼承HandleErrorAttribute,然后重寫OnException方法,加入自己的邏輯,例如將異常信息寫入日志文件等。當然,這并沒有任何不妥,但良好的設計應該是場景驅動的,是動態和可配置的。

      簡單地說,不同的場景有不同的需求,而我們的程序需要更好的面對變化。當然,繼承HandleErrorAttribute也完全可以實現上面所說的,只不過這里我不打算去擴展它,而是重新編寫一個模塊,并且可以與原有的HandleErrorAttribute共同使用。

      下面讓我們一起來學習ASP.NET MVC異常處理模塊編程實例吧!

      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會被執行,瀏覽器也會出現我們配置的錯誤頁面。

    【ASP.NET MVC異常處理模塊簡單教程-ASP.NET教程實例】相關文章:

    PS摳紅花的處理教程04-01

    最佳的 Node.js 教程結合實例03-19

    asp.net的學習過程講解03-30

    教你讀懂ps直方圖的實例教程據介紹04-02

    CAD2012教程之超級填充實例01-29

    ASP.NET Page函數調用解析03-29

    調酒教程03-08

    學習簡單的踢踏舞教程03-19

    簡單易學踢踏舞教程03-19

    主站蜘蛛池模板: 国产亚洲精品无码成人| 国产精品免费AV片在线观看| 在线成人精品国产区免费| 青青草原综合久久大伊人精品| 四虎成人精品在永久在线| 久久线看观看精品香蕉国产| 最新国产成人精品2024| 国产精品xxxx国产喷水亚洲国产精品无码久久一区 | 亚洲国产精品热久久| 久久亚洲美女精品国产精品| 欧美成人精品一区二三区在线观看| 精品一区二区在线观看| 久久香蕉国产线看观看精品yw| 欧美精品黑人粗大| 国产伦精品一区二区三区视频猫咪 | 亚洲第一永久AV网站久久精品男人的天堂AV| 日韩欧精品无码视频无删节| 精品久久久无码中文字幕| 91精品在线国产| 久久精品国产久精国产| 2018国产精华国产精品| 久久精品中文字幕无码绿巨人| 亚洲精品无码永久在线观看| 久久精品无码一区二区app| 国产精品久久久天天影视香蕉| 欧美精品免费观看二区| 国产精品久久久福利| 国产AV午夜精品一区二区三区 | 亚洲综合一区二区精品导航| 国产亚洲美女精品久久久久狼 | 国产乱人伦偷精品视频| 在线电影国产精品| 久久国产精品久久精品国产| 国产AV无码专区亚洲精品 | 精品国偷自产在线| 午夜天堂精品久久久久| 亚洲麻豆精品国偷自产在线91| 日韩精品无码Av一区二区| 日韩精品一区二三区中文 | 国产精品久操视频| 国产精品你懂的在线播放|