I follow this article to implement Custom Error Pages and Error Logging. The logging works fine. However, the custom error page doesn’t display for ajax request when exception occured, it works for normal http full request, e.g.
http://localhost/MyApp/Report/Create/17/ , work, normal url request
http://localhost/MyApp/Report/CreateUser/17/json, NOT work, using Ajax
ASP.NET MVC HandleError Attribute, Custom Error Pages and Logging Exceptions
public class BaseController : Controller
{
protected override void OnException(ExceptionContext filterContext)
{
base.OnException(filterContext);
_log.Error("Error Logging", filterContext.Exception);
// Output a nice error page when customErrors's mode = On.
if (filterContext.HttpContext.IsCustomErrorEnabled)
{
filterContext.ExceptionHandled = true;
this.View("Error").ExecuteResult(this.ControllerContext);
}
}
}
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
//Display custom error page using controller.OnException(), HandleErrorAttribute has to be disabled.
//filters.Add(new HandleErrorAttribute());
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
web.config
<customErrors mode="On">
</customErrors>
Any idea would very much appreciated.
AJAX request are treated different from standard HTML GET\POST request as the browser does not provide automatic rendering of the result. This would be true for any backend stack (not limited to ASP.Net MVC). So in this case even if response contains complete html for error page (which i doubt ASP.Net MVC does for AJAX calls), the browse would not automatically redirect to error page
The way to go about it would be to catch exception in AJAX and redirect to the error page from client side.