在系统出现未处理的错误时,在Global的Application_Error记录下错误
??????? 在我們開發(fā)系統(tǒng)時(shí),一般都會(huì)記錄日志信息,這樣方便日后進(jìn)行維護(hù),同時(shí)如果系統(tǒng)出現(xiàn)了錯(cuò)誤,也會(huì)方便查找,很多
系統(tǒng)開發(fā)時(shí)都會(huì)使用成熟的日志組件,如log4net。但是我今天要介紹的不是日志組件,而是在某些特別的情況下,我們沒有
能捕獲錯(cuò)誤該怎么辦???
??????? 正如標(biāo)題所說的,我們可以在Global文件的Application_Error中對(duì)錯(cuò)誤進(jìn)行捕獲,并記錄下來。
下面就來看看下面一段示例代碼:
protected void Application_Error(object sender, EventArgs e)
??????? {
??????????? // 在出現(xiàn)未處理的錯(cuò)誤時(shí)運(yùn)行,獲取錯(cuò)誤
??????????? 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;
??????????????? //跳轉(zhuǎn)到系統(tǒng)出錯(cuò)頁(yè)面
??????????????? Response.Redirect("~/SystemError.aspx");
??????????? }
??????? }
轉(zhuǎn)載于:https://www.cnblogs.com/kevinGao/archive/2012/01/14/2323342.html
《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的在系统出现未处理的错误时,在Global的Application_Error记录下错误的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PATA1001A+BFormat
- 下一篇: Windows 7 shortcut i