So from my understanding you want to redirect the user to a particular error page on exception and also from the error page you want to access the exception.
Here is what I've tried, created a base controller and overridden the OnException
method. Inside the OnException
method I'm doing most of the things you are trying in the Global.asax.cs
.
Most importantly after handling the exception I'm setting a RedirectAction
in the Result
property of the ExceptionContext
.
Also to access the Exception
from the error views I've stored the exception in the TempData
. From the ErrorController
I'm passing the exceptions as HandleErrorInfo
instances to the views.
Here is the complete code.
// BaseController
public class BaseController : Controller
{
protected override void OnException(ExceptionContext filterContext)
{
if (!filterContext.ExceptionHandled)
{
var action = "General";
if (filterContext.Exception is HttpException)
{
var httpException = filterContext.Exception as HttpException;
switch (httpException.GetHttpCode())
{
case 404:
// page not found
action = "Error404";
break;
case 500:
// server error
action = "Error500";
break;
default:
action = "General";
break;
}
}
filterContext.Result = RedirectToAction(action, "error");
TempData["error"] = new HandleErrorInfo(filterContext.Exception,
RouteData.Values["controller"].ToString(),
RouteData.Values["action"].ToString());
filterContext.ExceptionHandled = true;
}
}
}
// Error Controller
public class ErrorController : Controller
{
public ActionResult Error404()
{
return View(TempData["error"] as HandleErrorInfo);
}
// other methods
}
// Sample controller derives from BaseController.
public class HomeController : BaseController
{
public ActionResult Index()
{
return View();
}
public ActionResult NotFound()
{
throw new HttpException(404, "Not Found");
}
}
// Error404.cshtml
@model System.Web.Mvc.HandleErrorInfo
@{
ViewBag.Title = "404 Not Found";
}
<h2>@ViewBag.Title</h2>
<p>
Last Exception: @Model.Exception
</p>
UPDATE: One disadvantage with this approach is we can handle the HTTP exceptions 404, 500 or whatever if it is thrown only from the controller actions.