在系统出现未处理的错误时,在Global的Application_Error记录下错误
??????? 在我們開發系統時,一般都會記錄日志信息,這樣方便日后進行維護,同時如果系統出現了錯誤,也會方便查找,很多
系統開發時都會使用成熟的日志組件,如log4net。但是我今天要介紹的不是日志組件,而是在某些特別的情況下,我們沒有
能捕獲錯誤該怎么辦???
??????? 正如標題所說的,我們可以在Global文件的Application_Error中對錯誤進行捕獲,并記錄下來。
下面就來看看下面一段示例代碼:
protected void Application_Error(object sender, EventArgs e)
??????? {
??????????? // 在出現未處理的錯誤時運行,獲取錯誤
??????????? Exception objErr = Server.GetLastError().GetBaseException();
??????????? if (objErr != null)
??????????? {
??????????????? string error = "Error Page: " + Request.Url.ToString() + "<br>";
??????????????? if (objErr.Message != null)
??????????????? {
??????????????????? error += "Error Message: " + objErr.Message + "<br>";
??????????????? }
??????????????? if (objErr.StackTrace != null)
??????????????? {
??????????????????? error += "Stack Message:" + objErr.StackTrace + "<br>";
??????????????? }
??????????????? if (objErr.InnerException != null)
??????????????? {
??????????????????? error += "InnerException" + objErr.InnerException.Message + "<br>";
??????????????? }
??????????????? string strSystemLog = "GlobalSystemLog.Log";
??????????????? string strSystemLogpath = Server.HtmlEncode(strSystemLog);
??????????????? FileInfo fi = new FileInfo(strSystemLogpath);
??????????????? if (File.Exists(strSystemLogpath))
??????????????? {
??????????????????? using (StreamWriter sw = fi.AppendText())
??????????????????? {
??????????????????????? sw.WriteLine();
??????????????????????? sw.WriteLine(DateTime.Now.ToShortTimeString() + "\n" + error + "\n");
??????????????????????? sw.Close();
??????????????????? }
??????????????? }
??????????????? else
??????????????? {
??????????????????? using (StreamWriter sw = fi.CreateText())
??????????????????? {
??????????????????????? sw.WriteLine();
??????????????????????? sw.WriteLine(DateTime.Now.ToShortTimeString() + "\n" + error + "\n");
??????????????????????? sw.Close();
??????????????????? }
??????????????? }
??????????????? Server.ClearError();
??????????????? Application["error"] = error;
??????????????? //跳轉到系統出錯頁面
??????????????? Response.Redirect("~/SystemError.aspx");
??????????? }
??????? }
轉載于:https://www.cnblogs.com/kevinGao/archive/2012/01/14/2323342.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的在系统出现未处理的错误时,在Global的Application_Error记录下错误的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PATA1001A+BFormat
- 下一篇: SolidWorks学习笔记4特征