Custom ErrorHandling action filter that catches on

2019-07-21 12:51发布

问题:

I have implemented the following action filter to handle ajax errors:

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;
        }
    }

I want the filter to be able to catch only certain types of errors and use it like this in the controller action:

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

How can this happen? Thanks!

回答1:

I take it you're looking for this: http://msdn.microsoft.com/en-us/library/aa288454%28v=vs.71%29.aspx#vcwlkattributestutorialanchor1

To give the attribute a parameter you can either make a nonstatic property or have a constructor. In your case it'd look something like this:

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;
    }
}