Redirect from OnException method to a View in MVC 3

All controller class should by default inherit the Controller class. And in the controller class we have the OnException() method. This method is called whenever an unhandled exception occurs in an action.

Below is the code using which we can redirect to a view using the OnException method. Also note that we can use the filterContext.Exception which we have stored in the Session on the error view to show a nice error message.

protected override void OnException(ExceptionContext filterContext)  
this.Session["ExceptionMessage"] = filterContext.Exception; // Can use this exception message later on.
filterContext.ExceptionHandled = true;
filterContext.Result = this.RedirectToAction("Error", "Home"); // Redirect to error page.