kick it on DotNetKicks.com   Shout it  

ASP.NET MVC Error Handling

When working with the latest MVC release (Preview 2) I was having trouble working with the Application_Error event in global.asax. While this does work if you want to redirect to an html file, if you want to redirect to an aspx file you need to use the Controller.OnActionExecuted method. Here's an example:

        protected override void OnActionExecuted(FilterExecutedContext filterContext)
{
if (filterContext.Exception != null)
{
Exception ex = filterContext.Exception;
if (ex.InnerException != null)
ex = ex.InnerException;

filterContext.ExceptionHandled = true;

RedirectToAction(new RouteValueDictionary(new
{
Controller = "Error",
Action = "Error",
Message = ex.Message
}));
}

base.OnActionExecuted(filterContext);
}

UPDATE 7/8/09: as of the final RTM for MVC the signature for OnActionExecuted has changed, it now reads : void OnActionExecuted(ActionExecutedContext). Thanks to jobr31 for reminding me to update the information.

I imagine if you wanted to use Application_Error you could use a different extension, like ".err" and configure ASP.NET to map the extension to the Page HttpHandler. But it seems like too much work to me to even try it when this works perfectly fine.

A more extensible method would be to use Action Filters. I have seen an example demonstrated by Troy Goode, but I haven't tried it yet.

Tags: ,

kick it on DotNetKicks.com   Shout it  

Feedback

# 

Gravatar The name of FilterExecutedContext seems to have been renamed to ActionExecutedContext in the RTM version of MVC. 7/8/2009 5:31 AM | noreply@blogger.com (jobr31)

# 

Gravatar You're right, I guess I need to review my old MVC posts and update them with RTM changes. 7/8/2009 5:50 AM | noreply@blogger.com (Mark J. Miller)

# 

Gravatar Very helpful but now there is another eventhandler that may not have existed in RC2.

You can override Controller.OnException. Also instead of doing a redirect, you could generate a view and set it as the filterContext.Result. This is nice when you don't have to have a 200 -> 302 condition and want to just have a 404 as below.

protected override void OnException(ExceptionContext filterContext)
{
//InvalidOperationException is thrown if the path to the view cannot be resolved by the viewengine
if (filterContext.Exception is InvalidOperationException)
{
filterContext.ExceptionHandled = true;
filterContext.Result = View("NotFound");
filterContext.HttpContext.Response.StatusCode = 404;
}

base.OnException(filterContext);
} 7/22/2009 9:27 PM | noreply@blogger.com (jwalker)

Post a comment





 

Please add 2 and 3 and type the answer here:

 

 

Copyright © Mark J. Miller