2013-05-07 60 views
0

即使發生未處理的異常,也會調用Page_Unload。我需要處理這種情況。如何在Page_Unload中檢測到已發生未處理的異常?

當變量在Page_Unload中處於不正確的狀態時,我有一個變量狀態驗證拋出異常。 Application_ErrorGlobal.asax後處理的例外。當另一個異常已經發生時,我需要禁止引發異常。

頁:

public partial class _Default : System.Web.UI.Page 
{ 
    private int tst = 0; 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     tst = tst/tst; //causes "Attempted to divide by zero." 
     tst = 1; 
    } 
    protected void Page_Unload(object sender, EventArgs e) 
    { 
     if (tst == 0) throw new Exception("Exception on unload"); 
    } 
} 

的Global.asax:

void Application_Error(object sender, EventArgs e) 
{ 
    // Get the error details 
    Exception lastErrorWrapper = Server.GetLastError(); 
    System.Diagnostics.Debug.Print(lastErrorWrapper.Message); 
} 

我需要得到「試圖除以零。」Global.asax但我正在逐漸「上卸載例外」

給出大幅度簡化的例子。真實情況包括用戶控制和條件編譯。

我不能解決Page_Load的情況(例如通過捕捉異常)。

+0

我編輯了你的標題。請參閱:「[應該在其標題中包含」標籤「](http://meta.stackexchange.com/questions/19190/)」,其中的共識是「不,他們不應該」。 – 2013-05-07 10:41:25

回答

0

你爲什麼不使用Global.asax的方法,這樣

void Application_Error(object sender, EventArgs e) 
     { 
      // Code that runs when an unhandled error occurs 
      // Get the error details 
      Exception lastErrorWrapper = Server.GetLastError();    
      System.Diagnostics.Debug.Print(lastErrorWrapper.Message); 
      Response.Redirect("~/error.aspx?q=" + lastErrorWrapper.Message); 
     } 

然後,它不會顯示在這裏的錯誤,替代的是:在web.config中

組自定義錯誤頁

<customErrors mode="On" defaultRedirect="mypage.aspx"> 
    </customErrors> 

Regards

+0

我在實際應用中以這種方式使用它。所提供的代碼僅是一個簡單的例子。但它不能解決問題 - 獲得不同的信息而不是拋出。 – IvanH 2013-05-07 10:12:10

+0

然後一個更好的例子是最好有一個控制和實際的數據/異常@IvanH – Alok 2013-05-07 10:17:37

+0

問題是要麼禁止引發Page_Unload或以某種方式得到Application_Error「以前的異常」。發生的異常未知。如果我知道這個例外,我會阻止它而不是顯示它。 – IvanH 2013-05-07 10:36:52

相關問題