以前不知道从哪里找到的处理全局异常的,觉得蛮好用就记下来了。
1, 建立MyExecptionAttribute.cs类,写入如下代码:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
-
- namespace Niunan.MVCShop.Code
- {
- public class MyExecptionAttribute : HandleErrorAttribute
- {
- public static Queue<Exception> ExceptionQueue = new Queue<Exception>();
-
- public override void OnException(ExceptionContext filterContext)
- {
-
- ExceptionQueue.Enqueue(filterContext.Exception);
-
- base.OnException(filterContext);
- }
- }
- }
2,在Global文件代码如下:
- using Niunan.Utility;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading;
- using System.Web;
- using System.Web.Http;
- using System.Web.Mvc;
- using System.Web.Routing;
-
- namespace Niunan.MVCShop
- {
-
-
- public class MvcApplication : System.Web.HttpApplication
- {
- protected void Application_Start()
- {
- AreaRegistration.RegisterAllAreas();
-
- WebApiConfig.Register(GlobalConfiguration.Configuration);
- RouteConfig.RegisterRoutes(RouteTable.Routes);
-
- GlobalFilters.Filters.Add(new Code.MyExecptionAttribute());
-
-
- string filePath = Server.MapPath("/Log/");
- ThreadPool.QueueUserWorkItem(o =>
- {
- while (true)
- {
- try
- {
- if (Code.MyExecptionAttribute.ExceptionQueue.Count > 0)
- {
- Exception ex = Code.MyExecptionAttribute.ExceptionQueue.Dequeue();
-
- if (ex != null)
-
- {
- Tool.TxtLog(ex.ToString(), filePath + DateTime.Now.ToString("yyyyMMdd")+".txt");
- }
- else
- {
- Thread.Sleep(30);
- }
- }
- else
- {
- Thread.Sleep(30);
- }
- }
- catch (Exception ex)
- {
- Code.MyExecptionAttribute.ExceptionQueue.Enqueue(ex);
-
- }
- }
-
- }, filePath);
- }
- }
- }
|
请发表评论