views:

469

answers:

1

I am trying to implement Error handling using Action Filters Attributes as per ScottGu's blog

My code is as follows:

[HandleError]
[HandleError(ExceptionType = typeof(NullReferenceException), View = "CustomError")]
public class ArticlesController : Controller
{
    public object OhDearACrash()
    {
        throw new Exception("Oh Dear");
    }

    public object NullRefCrash()
    {
        throw new NullReferenceException();
    }

I am encountering an issue where I am never able to hit the CustomError view as I receive an exception when the exception is thrown

OhDearACrash: Exception was unhandled by user code

NullRefCrash: NullReferenceException was unhandled by user code

and so the unhandled exception is picked up by the Default [HandleError] which routes to View/Shared/Error.aspx which handles the error.

How do I handle the unhandled exception?

+3  A: 

The action filters are executed one by one. In your case, the problem is probably that the generic HandleError action filter is executed before the specific one.

You can influence the order of execution by setting the 'Order' property of your action filter:

[HandleError(Order = 2)]
[HandleError(Order = 1, ExceptionType = typeof(NullReferenceException), View = "CustomError")]
public class ArticlesController : Controller
{
}
jeroenh
This worked and enabled me to hit CustomError, thanks!
Nicholas Murray
If as Scott says 'You can alternatively specify specific exception types you are interested in catching, and specify custom error views for them by specifying the "ExceptionType" and "View" properties on [HandleError] attributes:' why do I need an Order when I am specifying the Exception Type?
Nicholas Murray
If the generic HandleError filter is hit first, it will handle the exception (any exception, so also your NullReference exception). Your second HandleError action filter will not be hit anymore.
jeroenh
Yes thanks, looked up MSDN and it says 'If no order number is specified, the order number is -1. This means that the filter is applied before any other HandleErrorAttribute filters, except other filters whose order is also -1.' and 'Filters with the same order number are applied in an undetermined order.' so of course that's why the HandleError filter could be hit first.
Nicholas Murray