asp.net錯誤處理Application_Error事件樣本_實用技巧

來源:互聯網
上載者:User

ASP.NET錯誤處理方法Application_Error事件舉例如下:

建立web程式——建立AppEvent.aspx頁面——在該頁面中添加如下代碼:

複製代碼 代碼如下:

<SCRIPT language=C# runat="server">
void Page_Load(object sender, System.EventArgs e)
{
throw(new ArgumentNullException());
}
</SCRIPT>

然後呢,將Application_Error事件添加到Global.asax檔案中以捕獲在AppEvent.aspx 頁的 Page_Load 事件中引發的錯誤。將以下代碼添加到 Global.asax 檔案中:

複製代碼 代碼如下:

protected void Application_Error(object sender, EventArgs e)
{
Exception objErr = Server.GetLastError().GetBaseException(); //擷取錯誤 keleyi.com
string err ="Error Caught in Application_Error event/n" +
"Error in:" + Request.Url.ToString() +
"/nError Message:"+ objErr.Message.ToString() +
"/nStack Trace:"+ objErr.StackTrace.ToString();
//將捕獲的錯誤寫入windows的應用程式記錄檔中,可從事件檢視器中訪問應用程式記錄檔。
System.Diagnostics.EventLog.WriteEntry("Test2", err, System.Diagnostics.EventLogEntryType.Error);
Server.ClearError(); //清除異常,其他地方不再捕獲此異常。
}

儲存剛才所做的操作,在 Visual Studio .NET 中,在產生菜單上,單擊產生。按右鍵該頁,然後單擊在瀏覽器中查看。在這種情況下該頁將為空白,但是您應該注意到在事件記錄中已添加了一個新項。本樣本在應用程式記錄檔中產生一個項,可從事件檢視器訪問應用程式記錄檔。在記錄錯誤之後,您可能希望將使用者重新導向到另一個方便使用的錯誤頁或者根據需要執行一些其他動作,這些操作可以根據自己的需要來做。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.