ASP.NET MVC 3: Set up custom error pages to handle errors in “non-AJAX” requests and jQuery AJAX requests


In this blog post I will show how to set up custom error pages in ASP.NET MVC 3 applications to create user-friendly error messages instead of the (yellow) IIS default error pages for both “normal” (non-AJAX) requests and jQuery AJAX requests.

In this showcase we will implement custom error pages to handle the HTTP error codes 404 (“Not Found”) and 500 (“Internal server error”) which I think are the most common errors that could occur in web applications. In a first step we will set up the custom error pages to handle errors occurring in “normal” non-AJAX requests and in a second step we add a little JavaScript jQuery code that handles jQuery AJAX errors.

We start with a new (empty) ASP.NET MVC 3 project and activate custom errors in the Web.config by adding the following lines under <system.web>:


  
  

Note: You can set mode=”Off” to disable custom errors which could be helpful while developing or debugging. Setting mode=”RemoteOnly” activates custom errors only for remote clients, i.e. disables custom errors when accessing via http://localhost/[…]. In this example setting mode=”On” is fine since we want to test our custom errors. You can find more information about the <customErrors> element here.

In a next step we remove the following line in Global.asax.cs file:

filters.Add(new HandleErrorAttribute());

and add a new ErrorController (Controllers/ErrorController.cs):

public class ErrorController : Controller
{
  public ActionResult Index()
  {
    return InternalServerError();
  }

  public ActionResult NotFound()
  {
    Response.TrySkipIisCustomErrors = true;
    Response.StatusCode = (int)HttpStatusCode.NotFound;
    return View("NotFound");
  }

  public ActionResult InternalServerError()
  {
    Response.TrySkipIisCustomErrors = true;
    Response.StatusCode = (int)HttpStatusCode.InternalServerError;
    return View("InternalServerError");
  }
}

In a last step we add the ErrorController‘s views (Views/Error/NotFound.cshtml and Views/Error/InternalServerError.cshtml) that defines the (error) pages the end user will see in case of an error. The views include a partial view defined in Views/Shared/Error/NotFoundInfo.cshtml respectively Views/Shared/Error/InternalServerErrorInfo.cshtml that contains the concrete error messages. As we will see below using these partial views enables us to reuse the same error messages to handle AJAX errors.

Views/Error/NotFound.cshtml:

@{
  ViewBag.Title = "Not found";
}
@{
  Html.RenderPartial("Error/NotFoundInfo");
}

Views/Shared/Error/NotFoundInfo.cshtml:

The URL you have requested was not found.

Views/Error/InternalServerError.cshtml:

@{
  ViewBag.Title = "Internal server error";
}
@{
  Html.RenderPartial("Error/InternalServerErrorInfo");
}

Views/Shared/Error/InternalServerErrorInfo.cshtml:

An internal Server error occured.

To handle errors occurring in (jQuery) AJAX calls we will use jQuery UI to show a dialog containing the error messages. In order to include jQuery UI we need to add two lines to Views/Shared/_Layout.cshtml:



Moreover we add the following jQuery JavaScript code (defining the global AJAX error handling) and the Razor snippet (defining the dialog containers) to Views/Shared/_Layout.cshtml:


@{ Html.RenderPartial("Error/NotFoundInfo"); }
@{ Html.RenderPartial("Error/InternalServerErrorInfo"); }

As you can see in the Razor snippet above we reuse the error texts defined in the partial views saved in Views/Shared/Error/.

To test our custom errors we define the HomeController (Controllers/HomeController.cs) as follows:

  public class HomeController : Controller
  {
  public ActionResult Index()
  {
    return View();
  }
  public ActionResult Error500()
  {
    throw new Exception();
  }
}

and the corresponding view Views/Home/Index.cshtml:

@{
  ViewBag.Title = "ViewPage1";
}



  • @Html.ActionLink("Error 404 (Not Found)", "Error404")
  • @Html.ActionLink("Error 404 (Not Found) [AJAX]", "Error404", new { }, new { Class = "ajax" })
  • @Html.ActionLink("Error 500 (Internal Server Error)", "Error500")
  • @Html.ActionLink("Error 500 (Internal Server Error) [AJAX]", "Error500", new { }, new { Class = "ajax" })

To test the custom errors you can launch the project and click one of the four links defined in the view above. The “AJAX links” should open a dialog containing the error message and the “non-AJAX” links should redirect to a new page showing the same error message.

You can download the Visual Studio 2010 project containing all the source code here.

Summarized this blog post shows how to set up custom errors that handle errors occurring in both AJAX requests and “non-AJAX” requests. Depending on the project, one could customize the example code shown above to handle other HTTP errors as well or to show more customized error messages or dialogs.

When thinking about error handling in ASP.NET MVC 3 applications you should take a look at ELMAH (Error Logging Modules and Handlers for ASP.NET), a tool that logs/handles errors on server side and which works perfectly in combination with the approach shown above. I wrote a blog post about how to set up and configure ELMAH in a ASP.NET MVC application.

,

6 responses to “ASP.NET MVC 3: Set up custom error pages to handle errors in “non-AJAX” requests and jQuery AJAX requests”

  1. Great post! The key thing is that the http status code can be set properly for ajax calls and also a user friendly page for viewers! and it’s all handled in one place. Nice Work!

    Test this method a little bit and it’s interesting that HandleError always kicks in when the customErrors is turned on no matter the controller is decorated with HandleError or not.. Unless I comment out this line..

    filters.Add(new HandleErrorAttribute());

  2. Is there a way to create a more generic error handler ? Something that would catch exceptions, parsing errors and so on?

  3. […] Custom error page may enhance the user experience when the visitors meet problems in your website rather than the default error page. After implementing log4net, I began to make the custom error page in asp.net MVC in the open source project. Here I would record what I did step by step to create simple 404/500 error page, base on this blog. […]

Leave a Reply

Your email address will not be published. Required fields are marked *