1.第一种做法,在 Web.config 文件配置
defaultRedirect 属性用来指明当 aspx 页面发生了未处理错误时导向的页面; 但
Asp.net 使用重定向机制来重新
导航错误页面,这样错误信息就会丢失,也就是说我们用 Server.GetLastError()获得的 Exception 对象始终是空的. 虽然可以提示用户出错, 并提供一个返回出错页面的链接,却不能给管理员一个很好的错误提示. 2.第二种做法:在 global 文件里的 Application_Error 方法中处理
代码 protected void Application_Error(Object sender, EventArgs e) { Exception ex=Server.GetLastError().GetBaseException();
string errorTime="发生时间:"+DateTime.Now.ToString(); string errorAddress="发生异常页:"+Request.Url.ToString(); string errorInfo="异常信息:"+ex.Message; string errorSource="错误源:"+ex.Source; string errorTrace="堆栈信息:"+ex.StackTrace; Server.ClearError();
System.IO.StreamWriter writer=null; try { lock(this) { //写入日志 string year=DateTime.Now.Year.ToString();
string month=DateTime.Now.Month.ToString(); string day=DateTime.Now.Day.ToString(); string path=string.Empty; string filename=DateTime.Now.ToString("yyyyMMdd") +".txt"; path=Server.MapPath("~/Error/")+year+month+day; if(!Directory.Exists(path)) { Directory.CreateDirectory(path); } System.IO.FileInfo file=new FileInfo(path+"/"+fil ename); writer=new StreamWriter(file.FullName,true);//文 件不在则创建,true 表示追加 writer.WriteLine("用户 IP:"+Request.UserHostAddres s); writer.WriteLine(errorTime); writer.WriteLine(errorAddress); writer.WriteLine(errorInfo); writer.WriteLine(errorSource); writer.WriteLine(errorTrace); writer.WriteLine("------------------------------------------------------");
} } finally { if(writer!=null) { writer.Close(); }
} Server.Transfer("~/ErrorPage.aspx"); //跳转到显示友好错误的页 面
}
然后在 ErrorPage.aspx 页面显示一些好友的提示信息. 3.第三种做法:在 Page_Error 事件里面处理
代码 private void Page_Load(object sender, System.EventArgs e) { throw(new ArgumentNullException()); }
public void Page_Error(object sender,EventArgs e) { Exception ex=Server.GetLastError().GetBaseException();
string errorTime="发生时间:"+DateTime.Now.ToString(); string errorAddress="发生异常页:"+Request.Url.ToString(); string errorInfo="异常信息:"+ex.Message; string errorSource="错误源:"+ex.Source; string errorTrace="堆栈信息:"+ex.StackTrace;
Server.ClearError();
System.IO.StreamWriter writer=null; try { lock(this) { //写入日志
string year=DateTime.Now.Year.ToString(); string month=DateTime.Now.Month.ToString(); string day=DateTime.Now.Day.ToString(); string path=string.Empty; string filename=DateTime.Now.ToString("yyyyMMdd") +".txt"; path=Server.MapPath("~/Error/")+year+month+day; if(!Directory.Exists(path)) { Directory.CreateDirectory(pa
th); } System.IO.FileInfo file=new FileInfo(path+"/"+fil ename); writer=new StreamWriter(file.FullName,true);//文 件不在则创建,true 表示追加 writer.WriteLine("用户 IP:"+Request.UserHostAddres s); writer.WriteLine(errorTime); writer.WriteLine(errorAddress); writer.WriteLine(errorInfo); writer.WriteLine(errorSource); writer.WriteLine(errorTrace); writer.WriteLine("--