views:

326

answers:

1

I am trying to implement Custom Error handling via Action Filter Attributes.

My code is as follows:

[HandleError (Order = 2)]
[HandleError (Order = 1, ExceptionType = typeof(NullReferenceException), View = "CustomError")]
public class ArticlesController : Controller
{

    public object OhDearACrash()
    {
        throw new Exception("Oh Dear");
    }

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

    public ActionResult ThrowNotImplemented()
    {
        throw new NotImplementedException();
    }

OhDearACrash and ThrowNotImplemented are both picked up by [HandleError] which renders the error message via Error.aspx located in Views/Shared.

For example with OhDearACrash:

Message = <%= ViewData.Model.Exception.Message %>

renders

Message = Oh Dear

NullRefCrash is picked up by the [HandeError] that deals with an ExceptionType = typeof(NullReferenceException).

When CustomError attempts to render the error message using

Message = <%= ViewData.Model.Exception.Message %>

the ViewData.Model is null and an exception is raised

System.NullReferenceException was unhandled by user code
Message="Object reference not set to an instance of an object."

To create CustomError.aspx I copied Error.aspx and pasted to my newly created Views/Error and renamed to CustomView.aspx.

Since Error.aspx and CustomError.aspx are essentially the same how is this occuring?

Edit:

I created a Test Project that only contains the above and the CustomError.aspx view works perfectly fine - Is there anyway to debug my existing project to find the issue?

+1  A: 

I just tried this on ASP.NET MVC 1.0 and I'm getting the correct behavior.

Is it possible that you have another filter somewhere else that is running and changing the error somehow?

Eilon
In theory no, its happening as I have described it. If I step through the code it goes from ThrowNotImplemented on to CustomError.aspx in the same way it would from OhDearACrash to Error.aspx.
Nicholas Murray
When I have copied the Error page in the Shared Views directory and pasted it back in there and renamed it MyError and referred to it via [HandleError(Order = 1, ExceptionType = typeof(NullReferenceException), View = "MyError")] it works, did you use the Views/Shared directory in your test?
Nicholas Murray