1. 程式人生 > >MVC 統一異常處理

MVC 統一異常處理

http 方法 ear ted public response n) text over

在出現異常時,我們不希望將錯語的原因讓客戶看見,常常會做一個404錯誤頁面,將所有發生的異常都跳至該頁面,並把異常信息寫在日誌中。步驟如下:

1、讓我們看看Global.asax頁面Application_Start()方法中有FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
}

2、F12,進去該方法中,為我們的自定義的異常處理器註冊

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {

            filters.Add(new MyExceptionAttribute()); //自定義過濾器
        }

3、添加類文件MyExceptionAttribute 開始寫們我們自定義的類,註意,這裏要繼承我們mvc的異常處理類HandleErrorAttribute,在這個類中我們定義了一個隊列,這個隊列就是用來

存放異常信息的。並在適當的時間將這些異常信息寫入日誌中,在哪裏進行寫入呢,請往下看。

public class MyExceptionAttribute : HandleErrorAttribute
    {
        /// <summary>
        /// 捕獲控制器方法中的異常
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnException(ExceptionContext filterContext)
        {
            exceptionQueue.Enqueue(filterContext.Exception);
            filterContext.HttpContext.Response.Redirect(
"/error.html"); //base.OnException(filterContext); } public static Queue<Exception> exceptionQueue = new Queue<Exception>(); }

4、同樣我們在Application_Start()開啟一個線程來將隊列中的信息寫信到日誌中

System.Threading.ThreadPool.QueueUserWorkItem(a => {
                while (true)
                {
                    if (MyExceptionAttribute.exceptionQueue.Count() > 0)
                    {
                        Exception ex = MyExceptionAttribute.exceptionQueue.Dequeue();
                        if (ex != null)
                        {
                            LogService.ErrorOperationString(ex.ToString());
                        }
                        else
                        {
                            System.Threading.Thread.Sleep(9000);
                        }

                    }
                    else
                    {
                        System.Threading.Thread.Sleep(9000);
                    }
                }

            }); 

至此一個完整的mvc異常處理就完成了。。。

MVC 統一異常處理