C# 异常处理保存

通过设置异常处理可以将错误信息保存到日志文件中,避免直接在前端显示

1.新建类MyExceptionAttribute

 1 public class MyExceptionAttribute : HandleErrorAttribute
 2     {
 3         public static Queue<Exception> ExecptionQueue = new Queue<Exception>();
 4         /// <summary>
 5         /// 可以捕获异常数据
 6         /// </summary>
 7         /// <param name="filterContext"></param>
 8         public override void OnException(ExceptionContext filterContext)
 9         {
10           
11             base.OnException(filterContext);
12             Exception ex = filterContext.Exception;
13             //写到队列
14             ExecptionQueue.Enqueue(ex);
15             //跳转到错误页面.
16             filterContext.HttpContext.Response.Redirect("/Error.html");
17         }
18     }
MyExceptionAttribute

2.创建错误网页Error.html。当发生错误时直接跳转到错误页。

3.在Global.asax文件Application_Start()方法中添加处理代码

 1 //开启一个线程,扫描异常信息队列。
 2             string filePath = Server.MapPath("/Log/");
 3             ThreadPool.QueueUserWorkItem((a) => {
 4                 while (true)
 5                 {
 6                     //判断一下队列中是否有数据
 7                     if (MyExceptionAttribute.ExecptionQueue.Count() > 0)
 8                     {
 9                         Exception ex=MyExceptionAttribute.ExecptionQueue.Dequeue();
10                         if (ex != null)
11                         {
12                             //将异常信息写到日志文件中。
13                             string fileName = DateTime.Now.ToString("yyyy-MM-dd");
14                             File.AppendAllText(filePath+fileName+".txt",ex.ToString(),System.Text.Encoding.UTF8);
15                             
16                         }
17                         else
18                         {
19                             //如果队列中没有数据,休息
20                             Thread.Sleep(3000);
21                         }
22                     }
23                     else
24                     {
25                         //如果队列中没有数据,休息
26                         Thread.Sleep(3000);
27                     }
28                 }
29             
30             
31             },filePath);
protected void Application_Start()

猜你喜欢

转载自www.cnblogs.com/huangtaiyi/p/10902720.html