views:

139

answers:

1

In my ASP.NET MVC app, I'm handling errors by overriding OnException in the controller. What is happening is that if a runtime error happens on the page, the Error.aspx page opens inside the page on which the error happened. Here's the code (with some extra error message stuff removed):

Protected Overrides Sub OnException(ByVal filterContext As System.Web.Mvc.ExceptionContext)
    MyBase.OnException(filterContext)

    filterContext.ExceptionHandled = True
    View("Error").ExecuteResult(ControllerContext)

End Sub

The Error.aspx page is in the Shared directory. As an example, say my View is of type Author, and my model has a Book table hanging off that and the user doesn't have read access on Book. When I try to reference

<%=Model.Books.Count>

the entire Error.aspx page shows up in the spot where the count was supposed to be. How do I get this to redirect to the error page and leave the problem page behind?

Update:

An easier example is to just put

<% Throw New Exception("b0rkd")%>

at the top of the view. The Error.aspx is fully rendered at the point where you put the exception, inside the original page.

+2  A: 

Edit

In the case where the exception occurs while processing the result, replacing the result won't work since the result is already being rendered. In this case, you could try clearing the existing results and rendering the error result explicitly.

protected override void OnException( ExceptionContext filterContext )
{
    filterContext.ExceptionHandled = true;
    filterContext.HttpContext.Response.ClearContent();
    ViewResult view = new ViewResult { ViewName = "Error" };
    view.ExecuteResult( filterContext.Controller.ControllerContext );
}

Original

Set the result on the filterContext to your error view instead of rendering the error view to the response.

 filterContext.ExceptionHandled = true;
 filterContext.Result = View("Error" );
tvanfosson
Make sense, but that doesn't seem to change anything - still rendering inside the original page.
gfrizzle
I see the problem now. The exception is coming as the result is being executed. At that point, it's too late to replace it. This would work if the exception occurred during the action execution. I'll update my answer.
tvanfosson
Bingo! Thanks for the edit - this wasn't an easy topic to research without knowing the right questions to ask.
gfrizzle