以前不知道从哪里找到的处理全局异常的,觉得蛮好用就记下来了。
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);//将异常信息入队.
- //filterContext.HttpContext.Response.Redirect("/error.html");
- 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
- {
- // 注意: 有关启用 IIS6 或 IIS7 经典模式的说明,
- // 请访问 http://go.microsoft.com/?LinkId=9394801
- 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()); //NET4建立的项目的话则是在APP_Stars/ConfigFilter.cs中
- //通过线程开启一个线程,然后不停的从队列中或数据
- 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);//避免了CPU空转。
- }
- }
- catch (Exception ex)
- {
- Code.MyExecptionAttribute.ExceptionQueue.Enqueue(ex);
- }
- }
- }, filePath);
- }
- }
- }