2012-12-30 35 views
0

我的意圖是在發生異常時記錄錯誤(我正在使用Log4Net),並將錯誤信息重定向到外觀漂亮的頁面。我有一個返回類型T對象的類,主要是一個DataSet。asp.net +例外和重定向

在我的Catch聲明中,我寫了這個,它可以工作,但我不確定是否有更合適的處理方式,有人請指教。謝謝。需要注意的是扔不能省略,因爲該類有:

 catch (Exception ex) 
     { 
      log.Error(ex); 
      HttpContext.Current.Response.Redirect("~/errorPage.aspx"); 
      throw ex; 
     } 
+0

你是否必須把這段代碼放在你想記錄的所有地方?如果是這樣,那麼在'Application_Error'塊的Global.asax中可能會更好;那麼你只需要一次。請注意,您可能需要檢查'ex.InnerException'來獲取實際的異常。而是使用'Server.Transfer'代替。 – Darren

+0

感謝您的建議,如果我將錯誤處理置於Global.ascx中,則頁面級別發生的錯誤將變爲未處理的異常並停止我的程序。它最終仍然去我的errorPage。如何防止程序停止。謝謝? – k80sg

+1

如果你在全局代碼中放置一個斷點,你會看到它被擊中。這就是要點;捕獲所有未處理的異常。你看到它停止你的程序,因爲你處於調試模式。 – Darren

回答

2

這取決於你想如何處理錯誤的頁面上,一般情況下,未處理的異常應該冒泡在gloabl到的Application_Error返回類型。 asax文件通用。這裏有一個簡單的方法來處理這個錯誤。

void Application_Error(object sender, EventArgs e) 
{ 
// Code that runs when an unhandled error occurs 
// Get the exception object. 
Exception exc = Server.GetLastError(); 

// Handle HTTP errors 
if (exc.GetType() == typeof(HttpException)) 
{ 
// The Complete Error Handling Example generates 
// some errors using URLs with "NoCatch" in them; 
// ignore these here to simulate what would happen 
// if a global.asax handler were not implemented. 
    if (exc.Message.Contains("NoCatch") || exc.Message.Contains("maxUrlLength")) 
    return; 

//Redirect HTTP errors to HttpError page 
    Server.Transfer("HttpErrorPage.aspx"); 
} 

    // For other kinds of errors give the user some information 
// but stay on the default page 
    Response.Write("<h2>Global Page Error</h2>\n"); 
Response.Write(
    "<p>" + exc.Message + "</p>\n"); 
    Response.Write("Return to the <a href='Default.aspx'>" + 
    "Default Page</a>\n"); 

// Log the exception and notify system operators 
ExceptionUtility.LogException(exc, "DefaultPage"); 
ExceptionUtility.NotifySystemOps(exc); 

// Clear the error from the server 
Server.ClearError(); 
}