2010-04-27

Exception handling in ASP.NET MVC. Clear the output when returning error view

Today spent half a day figuring out why my error handling code sometimes returns “strange” view, as if error page was rendered inside partial view in which exception occured. Which by the way is exactly what was happening.

Exception handling looked like:

public abstract class MyController : Controller

{

//… other stuff

protected override void OnException(ExceptionContext filterContext)
{

    //log exception
    var exception = filterContext.Exception;              
    var model = new ErrorModel(exception);
    filterContext.Result = View("Error", "Site", model);
    filterContext.ExceptionHandled = true;

}

}

Until finally I found the fix:

public abstract class MyController : Controller

{

//… other stuff

protected override void OnException(ExceptionContext filterContext)
{

    //log exception
    var exception = filterContext.Exception;              
    var model = new ErrorModel(exception);
    filterContext.Result = View("Error", "Site", model);

    filterContext.HttpContext.Response.Clear();
    filterContext.HttpContext.Response.StatusCode = 500;
 
    filterContext.ExceptionHandled = true;

}

}

No comments: