天天看點

asp.net mvc HandleErrorAttribute 異常錯誤處理 無效!

系統未知bug,代碼沒有深究。 

現象:filters.Add(new HandleErrorAttribute()); 使用了全局的異常處理過濾。

HandleErrorAttribute 核心代碼:

asp.net mvc HandleErrorAttribute 異常錯誤處理 無效!
asp.net mvc HandleErrorAttribute 異常錯誤處理 無效!

public virtual void OnException(ExceptionContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }
            if (filterContext.IsChildAction)
            {
                return;
            }
            if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
            {
                return;
            }
            Exception exception = filterContext.Exception;
            if (new HttpException(null, exception).GetHttpCode() != 500)
            {
                return;
            }
            if (!this.ExceptionType.IsInstanceOfType(exception))
            {
                return;
            }
            string controllerName = (string)filterContext.RouteData.Values["controller"];
            string actionName = (string)filterContext.RouteData.Values["action"];
            HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
            filterContext.Result = new ViewResult
            {
                ViewName = this.View,
                MasterName = this.Master,
                ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
                TempData = filterContext.Controller.TempData
            };
            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.StatusCode = 500;
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
        }      

View Code

 經過測試,下面這些代碼執行完成之後,頁面還是顯示黃頁黃頁。而不是系統 預設的Error視圖

web.config中配置:customErrors mode="RemoteOnly"

 filterContext.ExceptionHandled = true;

 filterContext.HttpContext.Response.Clear();

 filterContext.HttpContext.Response.StatusCode = 500;

 filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;

有一個項目情況一定是這樣的,其他好幾個項目正常。

修複代碼如下,使用自定義類繼承自HandleErrorAttribute  重寫方法OnException

加入代碼

base.OnException(filterContext);

if (filterContext.ExceptionHandled)

filterContext.HttpContext.ClearError();

關鍵代碼:filterContext.HttpContext.ClearError().

具體原因不明,還有待查證,那位大哥有碰到過??? 猜測可能和httpcontext最後執行的邏輯判斷有問題,比如config的配置,運作時參數的不一緻等

回家檢視asp.net的源代碼去,找找ExceptionHandled預計能找到點東西