Fork me on GitHub

Asp.net MVC3 异常全局过滤器处理


1、建立异常全局过滤器处理机制,在Gloabal.asax.cs文件中,有如下代码块:

     public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());//主要就是这样一个类
        }

2、查看源码可以看到:

 public class HandleErrorAttribute : FilterAttribute, IExceptionFilter
  {
    /// <summary>
    /// Called when an exception occurs.
    /// </summary>
    /// <param name="filterContext">The action-filter context.</param><exception cref="T:System.ArgumentNullException">The <paramref name="filterContext"/> parameter is null.</exception>
    public virtual void OnException(ExceptionContext filterContext);//看到这里我们就有办法进行自定义处理了
    /// <summary>
    /// Gets or sets the type of the exception.
    /// </summary>
    /// 
    /// <returns>
    /// The type of the exception.
    /// </returns>
    public Type ExceptionType { get; set; }
    /// <summary>
    /// Gets or sets the master view for displaying exception information.
    /// </summary>
    /// 
    /// <returns>
    /// The master view.
    /// </returns>
    public string Master { get; set; }
    /// <summary>
    /// Gets the unique identifier for this attribute.
    /// </summary>
    /// 
    /// <returns>
    /// The unique identifier for this attribute.
    /// </returns>
    public override object TypeId { get; }
    /// <summary>
    /// Gets or sets the page view for displaying exception information.
    /// </summary>
    /// 
    /// <returns>
    /// The page view.
    /// </returns>
    public string View { get; set; }
  }

3、我们新建一个类,并且继承自HandleErrorAttribute,然后重写OnException方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using log4net;

namespace MyEFTest.Models
{
    public class MyHandlerExceptionAttribute : HandleErrorAttribute
    {
        public override void OnException(ExceptionContext filterContext)
        {
            base.OnException(filterContext);
            //记录错误信息
            ILog log = log4net.LogManager.GetLogger(typeof (MyHandlerExceptionAttribute).FullName);
            log.Error(filterContext.Exception.ToString());
            //让当前请求 跳转到首页,或者错误页面
            filterContext.HttpContext.Response.Redirect("/ErrorPage.htm");//ErrorPage是自定义的错误页面
        }
    }
}

4、这样就OK了,只要程序遇到异常,就会跳到错误页面。

posted @ 2013-08-09 13:53  迁梦余光  阅读(508)  评论(0编辑  收藏  举报