Redirect from the OnException-method inside the controller with ASP.Net MVC

If your controller uses the HandleError-Attribute it handles exceptions thrown by action methods. I wanted to catch these exceptions and redirect to a custom error page. A simple RedirectToAction inside the OnException method does not work. But the ExceptionContext is all we need.

#region Error handling
protected override void OnException(ExceptionContext filterContext)
{
 // Make use of the exception later
 this.Session["ErrorException"] = filterContext.Exception;
 
 // Mark exception as handled
 filterContext.ExceptionHandled = true;
 
 // ... logging, etc
 
 // Redirect
 filterContext.Result = this.RedirectToAction("Error", "Home");
 
 base.OnException(filterContext);
}
#endregion

It stored the exception thrown inside the action onto the session. So this information is available inside my “error-action”.

My custom “error-action” even allows me to distinguish between normal requests and Ajax-requests (where I use a partial-view instead of a normal view) to display a nicer error message to the end-user.

7 Comments


  1. Hi Eric, i’m from Brazil, so excuse the bad english.
    Could you send me an example of the code above?
    I didn’t understand where to put this method “protected override void OnException”. I tried to put it on a custom handleerrorattribute class, but “this.Session” and “this.RedirectToAction” don’t worked at all. I’m using ASP.NET MVC 1.0 and .NET Framework 3.5 on VS2008.

    Thanks for your help. Greetings from Brazil.


  2. Hi Bruno,

    simply add this method inside your controller like so:

    [HandleError]
    public class HomeController : Controller
    {
      public ActionResult Index()
      {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";
     
        return View();
      }
     
      protected override void OnException(ExceptionContext filterContext)
      {
        base.OnException(filterContext);
      }
    }

    and add the code I provided in my post. The controllers reside in the controllers-folder within your MVC-project in Visual Studio.


  3. Thanks Eric. That worked just fine!


  4. Hello Eric, great help! Thanks!


  5. Hi

    You really helped me on this. I had been looking for this all over,

    Is there any similar solution for doing this in Application_Error() method of Global.asax ?


  6. only one post on MVC ! yet a life saving one 😉

Comments are closed.