自定义ErrorHandling操作过滤器,仅捕获特定类型的异常

时间:2013-07-23 09:24:50

标签: asp.net-mvc-3 asp.net-mvc-4

我已实现以下操作过滤器来处理ajax错误:

public class HandleAjaxCustomErrorAttribute : ActionFilterAttribute, IExceptionFilter
    {
        public void OnException(ExceptionContext filterContext)
        {
            if (!filterContext.HttpContext.Request.IsAjaxRequest()) return;

            filterContext.Result = AjaxError(filterContext.Exception.Message, filterContext);

            //Let the system know that the exception has been handled
            filterContext.ExceptionHandled = true;
        }
    }

我希望过滤器能够捕获某些类型的错误,并在控制器操作中使用它:

[HandleAjaxCustomErrorAttribute(typeof(CustomException))]
public ActionResult Index(){
 // some code
}

这怎么可能发生?谢谢!

1 个答案:

答案 0 :(得分:4)

我认为你正在寻找这个:http://msdn.microsoft.com/en-us/library/aa288454%28v=vs.71%29.aspx#vcwlkattributestutorialanchor1

要为属性提供参数,您可以创建非静态属性或具有构造函数。在你的情况下,它看起来像这样:

public class HandleAjaxCustomErrorAttribute : ActionFilterAttribute, IExceptionFilter
{
    private Type _exceptionType;

    public void OnException(ExceptionContext filterContext)
    {
        if (filterContext.Exception.GetType() != _exceptionType) return;
        if (!filterContext.HttpContext.Request.IsAjaxRequest()) return;

        filterContext.Result = AjaxError(filterContext.Exception.Message, filterContext);

        //Let the system know that the exception has been handled
        filterContext.ExceptionHandled = true;
    }

    public HandleAjaxCustomErrorAttribute(Type exceptionType)
    {
        _exceptionType = exceptionType;
    }
}