Exception Handling in MVC

Dheeraj Kumar Gunti

Reading Time : ( words)

Hello all, Welcome back to Knowledge Base.

Today we are going to talk about Exception Handling.... uhhhhhh Key Concept.

Exception Handling is the key component in every software program. We are very unfortunate that there will be certain situations where we experience errors. Either it could be with respect to network, data mismatch, casting issue or some thing which cause a booooommmmm error. But we should be cautious in handling those so user won't get distracted. If we won't handle them properly we will see the beautiful red screen with some errors in red......:(

Lets get started, we will see now how we can handle exceptions in MVC application. In this example, its a simple and one way of doing exception handling. This is just to get understanding and to start implementing exception handling.

As usual, lets create a MVC application. No Logic nothing, just straight forward a normal MVC application with default skeleton.

As a first step lets create a MVC View, here we are naming it as ErrorView.cshtml.

Create a simple layout for showing up if any error occurs.

Add customerror section in Web.Config. The reason behind this is to intimate the application that we are using custom error handling, so we are turning custom errors "on". We are even specifying the defaultRedirect for our custom errors.

Now in our controller, we are going to use built-in feature of handling errors by using HandleError attribute.

HandleAttribute, has some Named Properties which we need to configure based on our needs. The different named properties are,

  • ExceptionType. Specifies the exception type or types that the filter will handle. If this property is not specified, the filter handles all exceptions.
  • View. Specifies the name of the view to display.
  • Master. Specifies the name of the master view to use, if any.
  • Order. Specifies the order in which the filters are applied, if more than one HandleErrorAttribute filter is possible for a method.

(Courtesy: MSDN)

We are specifying the HandleError attribute in the controller at action level or we can specify them at controller level.

We need to register our custom filter in Global.asax.

Exception shows as below. We can customize this as per our needs.

Enjoy Coding...