Coding Tips & Tricks

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.

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

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.

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.

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.