.NET MVC处理全局异常的方法

在技术论坛上闲逛看到的一则处理全局异常的代码,摘记下来,以后方便使用过来看。

1, 建立MyExecptionAttribute.cs类,写入如下代码:
c#
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 ExceptionQueue = new Queue();//创建队列.

        public override void OnException(ExceptionContext filterContext)
        {
            //将异常信息入队.
            ExceptionQueue.Enqueue(filterContext.Exception);//将异常信息入队.
            //filterContext.HttpContext.Response.Redirect("/error.html");
            base.OnException(filterContext);
        }
    }
}
/c#

2,在Global文件代码如下:
c#
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://;.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);
        }
    }
}

你可能感兴趣的:(.NET MVC处理全局异常的方法)