Coding Tips & Tricks


Home>Error Handling

Custom error pages in MVC

I was recently looking for an efficient method of redirecting users to an error page when an exception is thrown in an MVC application. A useful way of doing this is with the HandleErrorAttribute. In order to handle exceptions thrown by your action methods, you need to mark your method with this attribute. The HandleErrorAttribute also allows you to use a custom page for this error.

Error

First you need to update your web.config file to allow your application to handle custom errors.

<system.web>
<
customErrors mode="On" >
</
system.web>

Then, your action method needs to be marked with the atttribute.

[HandleError]
public class HomeController : Controller
{
    [HandleError]
    public ActionResult ThrowException()
    {
        throw new ApplicationException();
    }
}

By calling the ThrowException action, this would then redirect the user to the default error page. In our case though, we want to use a custom error page and redirect the user there instead.So, let's create our new custom view page.

Next, we simply need to update the HandleErrorAttribute on the action method.

[HandleError]
public class HomeController : Controller
{
    [HandleError(View = "CustomErrorView")]
    public ActionResult ThrowException()
    {
      throw new ApplicationException();
    }
}

I found that I needed to update my web.config to also reflect the new custom error page.

<system.web>
       <
customErrors mode="On" defaultRedirect="CustomErrorView" >
</
system.web>

You can place your custom error page in the same directory as your view, or you can place it in the Shared view folder, either way this should work.

Unfortunately the HandleErrorAttribute wont work with 404 errors and 500 page errors. Ah, but what happens if I need to display a custom page? No problem, we just need to update our web.config and create an action method to handle the view.

<customErrors mode="On" defaultRedirect="CustomErrorView" >
       <
error statusCode="404" redirect="Error/Error404" />
       <
error statusCode="500" redirect="Error/Error500" />
</
customErrors>

The controller:
   

public class ErrorController : Controller
    {
// Return the 404 not found page
public ActionResult Error404()
{
return View();
}

// Return the 500 not found page
public ActionResult Error500()
{
return View();
}
    }

This could also be done with a static page if needed:

<customErrors mode="On" >
   <
error statusCode="404" redirect="Static404.html" />
</
customErrors>

There are a number of other ways of handling errors in MVC, but personally I have found this to work the best for me. You will want to add your own error logging on top of this, and this can be easily done in the controllers.

You can download a copy of the project here








Comments


Add your comment

300 Characters left


Please fill this in to confirm that you are human