之前不知道從哪裏找到的處理全局異常的,以爲蠻好用就記下來了。
1, 創建MyExecptionAttribute.cs類,寫入以下代碼:php
- 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文件代碼以下:html
- 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);
- }
- }
- }