I am using a combination of HandleErrorAttribute and a Custom Error Controller in the Custom Errors section for error handling in a MVC3 application. The logic is to handle any Ajax request errors via the OnException handler in the HandleErrorAttribute and rest of the errors via the ErrorController. Below is the code -
// Handle any ajax error via HandleErrorAttribute
public class HandleAjaxErrorAttribute : System.Web.Mvc.HandleErrorAttribute
{
public override void OnException(System.Web.Mvc.ExceptionContext filterContext)
{
filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
var exception = filterContext.Exception;
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
//some logic
filterContext.ExceptionHandled = true;
}
}
}
//Handle remaining errors in the Error Controller
public class ErrorController : Controller
{
protected override void HandleUnknownAction(string actionName)
{
var exception = Server.GetLastError(); //Can't get the exception object here.
//some logic
}
}
The Web.config settings:
<customErrors mode="On" defaultRedirect="~/Error">
</customErrors>
When any non-ajax exception occurs the control flows from the OnException block to the HandleUnknownAction in the Error Controller. However I am unable to get the Exception object. How can I get the Exception object in the Error Controller ?
Also, do you think this two step approach is a proper way to handle errors in MVC3 ? I thought of handling error in a centralized location using the Application_Error event handler but as per my research this is not the recommed approach for MVC applications.