一個簡單的ASP.NET MVC異常處理模塊

1、前言html

  異常處理是每一個系統必不可少的一個重要部分,它可讓咱們的程序在發生錯誤時友好地提示、記錄錯誤信息,更重要的是不破壞正常的數據和影響系統運行。異常處理應該是一個橫切點,所謂橫切點就是各個部分都會使用到它,不管是分層中的哪個層,仍是具體的哪一個業務邏輯模塊,所關注的都是同樣的。因此,橫切關注點咱們會統一在一個地方進行處理。不管是MVC仍是WebForm都提供了這樣實現,讓咱們能夠集中處理異常。web

  在MVC中,在FilterConfig中,已經默認幫咱們註冊了一個HandleErrorAttribute,這是一個過濾器,它繼承了FilterAttribute類和實現了IExceptionFilter接口,關於過濾器的執行過程,能夠看個人上一篇文章。說到異常處理,立刻就會聯想到500錯誤頁面、記錄日誌等,HandleErrorAttribute能夠輕鬆的定製錯誤頁,默認就是Error頁面;而記錄日誌咱們也只須要繼承它,並替換它註冊到GlobalFilterCollection便可。關於HandleErrorAttribute不少人都知道怎麼使用了,這裏就不作介紹了。瀏覽器

  ok,開始進入主題!在MVC中處理異常,相信開始不少人都是繼承HandleErrorAttribute,而後重寫OnException方法,加入本身的邏輯,例如將異常信息寫入日誌文件等。固然,這並無任何不妥,但良好的設計應該是場景驅動的,是動態和可配置的。例如,在場景一種,咱們但願ExceptionA顯示錯誤頁面A,而在場景二中,咱們但願它顯示的是錯誤頁面B,這裏的場景多是跨項目了,也多是在同一個系統的不一樣模塊。另外,異常也多是分級別的,例如ExceptionA發生時,咱們只須要簡單的恢復狀態,程序能夠繼續運行,ExceptionB發生時,咱們但願將它記錄到文件或者系統日誌,而ExceptionC發生時,是個較嚴重的錯誤,咱們但願程序發生郵件或者短信通知。簡單地說,不一樣的場景有不一樣的需求,而咱們的程序須要更好的面對變化。固然,繼承HandleErrorAttribute也徹底能夠實現上面所說的,只不過這裏我不打算去擴展它,而是從新編寫一個模塊,而且能夠與原有的HandleErrorAttribute共同使用。緩存

2、設計及實現框架

2.1 定義配置信息ide

  從上面已經能夠知道咱們要作的事了,針對不一樣的異常,咱們但願能夠配置它的處理程序,錯誤頁等。以下一個配置:測試

   <!--自定義異常配置-->
  <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中,保證它能夠隨時改隨時生效。ui

2.2 異常信息包裝對象spa

  這裏咱們定義一個實體對象,對應上面的節點。以下:

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

 

3、測試

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

4、總結

  事實上這只是一個比較簡單的例子,因此我稱它爲簡單的模塊,而是用框架、庫之類的詞。固然咱們能夠根據實際狀況對它進行擴展和優化。微軟企業庫視乎也集成這樣的模塊,有興趣的朋友能夠了解一下。

  源碼下載

相關文章
相關標籤/搜索