Application_Error位於Global.asax裏面,protected void Application_Error(object sender, EventArgs e)。當一個異常在調用堆棧中沒有被處理,也沒有被框架代碼處理時,我們說這個異常未處理,它將被ASP.NET捕獲,ASP.NET對此未處理錯誤的處理方法是顯示一個頁面,列出該未處理異常的詳細情況。我們可通過 Application_Error事件把錯誤寫進對應的文件裏面。
protected void Application_Error(object sender, EventArgs e) { System.IO.StreamWriter sw = new System.IO.StreamWriter(HttpContext.Current.Request.PhysicalApplicationPath + "\\errlog.txt", true, System.Text.Encoding.UTF8); Exception objErr = Server.GetLastError().GetBaseException(); string error = "發生異常頁: " + Request.Url.ToString() + "\n"; error += "異常信息: " + objErr.Message + "\n"; error += objErr.StackTrace + "\n"; if (error.IndexOf("文件不存在") < 0) { sw.WriteLine(DateTime.Now.ToString()); sw.WriteLine(error); ; } sw.Close(); sw.Dispose(); }
我們可以測試下。在項目中加入代碼
<script language="C#" runat="server"> void Page_Load(object sender, System.EventArgs e) { throw (new ArgumentNullException()); } </script>
運行(錯誤頁面)
這是寫入日誌的信息errlog.txt
2012/8/20 15:43:58
發生異常頁: http://localhost:2387/WebForm1.aspx
異常信息: 值不能爲 null。
在 ASP.webform1_aspx.Page_Load(Object sender, EventArgs e) 位置 f:\test2\login12\WebApplication1\WebApplication1\WebForm1.aspx:行號 10
在 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
在 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
在 System.Web.UI.Control.OnLoad(EventArgs e)
在 System.Web.UI.Control.LoadRecursive()
在 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
就算有了Application_Error,try...catch...還是需要的,爲了精確定位錯誤的類型及信息,提出精確的提醒信息。寫入日誌的信息還可以根據自己的需要更改。