ExceptionContext.ExceptionHandled 更改為 true。異常在哪里處理?
我正在使用全域操作過濾器來處理和記錄所有異常。
public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new ElmahHandleErrorAttribute()); filters.Add(new HandleErrorAttribute()); }這就是全域操作過濾器
ElmahHandleErrorAttribute的定義方式——它覆蓋了OnException方法。public class ElmahHandleErrorAttribute : System.Web.Mvc.HandleErrorAttribute { public override void OnException(ExceptionContext context) { //Is the exception handled already? context.ExceptionHandled seems to be true here if (!context.IsChildAction && (context.HttpContext.IsCustomErrorEnabled)) { //Do other stuff stuff //Log to Elmah } } ... }我不明白為什麼方法執行
context.ExceptionHandled時的值為真。OnException如何處理此異常?-編輯- 我
customErrors在Web.Config. 我有一個ErrorController班級,以及名為Generaland的動作Http404。<customErrors mode ="On" defaultRedirect="Error/General"> <error statusCode="404" redirect="Error/Http404"/> </customErrors>我不明白的是,控制器動作
General沒有執行(斷點永遠不會命中),但是當方法開始執行時,它的值ExceptionContext.ExceptionHandled設置為true 。OnException``ElmahHandleErrorAttribute
當發生異常時,全域過濾器的執行順序是相反的。這意味著
HandleErrorAttribute先執行。可以查看
HandleErrorAttribute這裡的程式碼,簡而言之就是:
- 僅在
ExceptionHandled為 false 時執行,並且啟用了自定義錯誤。- 設置重定向到錯誤視圖,預設情況下稱為
Error.- 設置
ExceptionHandled為真。因為它是第一個過濾器,
ExceptionHandled所以它在執行時為假,導致它將視圖設置為錯誤並設置ExceptionHandled為真。因此,當您自己的過濾器執行時,這就是為什麼ExceptionHandled已經設置為 true。請注意,如果自定義錯誤被禁用,那麼ExceptionHandled仍然是錯誤的,因為HandleErrorAttribute它不會完成它的工作。在這種情況下,ELMAH 無論如何都會記錄錯誤,因為它沒有被處理(黃色當機螢幕),所以你班級中的測試是為了防止重複記錄錯誤。現在,關於你的另一個問題,關於
General為什麼不執行操作,defaultRedirect只有在過濾器沒有自己設置一些顯式重定向時才使用它,所以當 ActionMethod 內部發生異常並且你HandleErrorAttribute註冊了全域過濾器時,它實際上被忽略了. 但是,如果您輸入了一個不存在的 URL,即不會在 ActionMethod 中發生的錯誤,它將被呼叫。此外,如果您註釋掉HandleErrorAttribute在 Global.asax.cs 中註冊的行,那麼您將始終General執行控制器操作。