ChrisP
ChrisP

Reputation: 10116

Why is custom HandleError attribute called with ExceptionHandled=true in MVC4 website?

In an MVC4 website the following custom HandleError attribute is registered

public class JHSHandleErrorAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
        {
            return;
        }

       //Handler for non-500 errors
        if (new HttpException(null, filterContext.Exception).GetHttpCode() != 500)
        {
            return;
        }
     ...

in Global.asax like this

protected static void RegisterMVCGlobalFilters(GlobalFilterCollection filters)
{
  //Add HandleError attribute as default for all controller exceptions
  filters.Add(new JHS.Web.Mvc.JHSHandleErrorAttribute
    {
      View = "Error/general"
    }, 1);

  filters.Add(new HandleErrorAttribute(), 2);

}

The custom HandleError attribute is called when an exception occurs and the filterContext.ExceptionHandled=true resulting in the standard error page to be displayed.

However, if the custom HandleError attribute is added to an individual action like this, the filterContext.Exceptionhandled=false and the rest of the method is executed resulting in the custom error view being displayed.

[JHS.Web.Mvc.JHSHandleError(View="Error/general")]
public ActionResult Index()
{

  throw new ArgumentNullException("test");
...

Why is the `filterContext.ExceptionHandled=true the custom view displayed when the custom error attribute is registered at the global level?

Upvotes: 0

Views: 986

Answers (1)

Grzegorz W
Grzegorz W

Reputation: 3517

The order of filter execution is described here and here. That still stands for MVC 4.

Basically filter registered on Global level (HandleErrorAttribute) gets executed before your custom filter defined on Action level.

This might seem strange - but that's how it is.

Upvotes: 2

Related Questions