在我们开发系统时,一般都会记录日志信息,这样方便日后进行维护,同时如果系统出现了错误,也会方便查找,很多
系统开发时都会使用成熟的日志组件,如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");
}
}
本文介绍了在ASP.NET中如何利用Global.asax文件中的Application_Error事件来捕获并记录未处理的异常。通过示例代码展示了如何获取异常信息,包括错误消息、堆栈跟踪和内部异常,然后将其写入日志文件,最后跳转到错误页面。
199

被折叠的 条评论
为什么被折叠?



