WebForm 在 Global.asax 中捕获全局异常

 1         /// 
 2         /// 捕获全局异常
 3         /// 
 4         /// sender
 5         /// e
 6         protected void Application_Error(Object sender, EventArgs e)
 7         {
 8             Exception ex = Server.GetLastError().GetBaseException();
 9             string ip = Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR") == null ?
10                 Request.ServerVariables.Get("Remote_Addr").ToString().Trim() :
11                 Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR").ToString().Trim();
12             string logpath = Server.MapPath("~/Log/" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt");
13             StringBuilder builder = new StringBuilder();
14             builder.AppendLine(string.Format("==========  {0} Application_Error BEGIN ==========", DateTime.Now));
15             builder.AppendLine("Ip:" + ip);
16             builder.AppendLine("浏览器:" + Request.Browser.Browser.ToString());
17             builder.AppendLine("浏览器版本:" + Request.Browser.MajorVersion.ToString());
18             builder.AppendLine("操作系统:" + Request.Browser.Platform.ToString());
19             builder.AppendLine("页面:" + Request.Url.ToString());
20             builder.AppendLine("错误信息:" + ex.Message);
21             builder.AppendLine("错误源:" + ex.Source);
22             builder.AppendLine("异常方法:" + ex.TargetSite);
23             builder.AppendLine("堆栈信息:" + ex.StackTrace);
24             builder.AppendLine("==========  Application_Error END  ===================");
25 
26             lock (logpath)
27             {
28                 try
29                 {
30                     using (var writer = new StreamWriter(logpath, true))
31                     {
32                         writer.Write(builder.ToString());
33                     }
34                 }
35                 catch
36                 {
37                     // 防止写文件时,文件被人为打开无法写入等
38                     // 记录日志报错不做处理,不应影响用户继续使用
39                 }
40             }
41 
42             Server.ClearError();
43             Response.Redirect("~/Error.htm");
44         }

 

你可能感兴趣的:(WebForm 在 Global.asax 中捕获全局异常)