Ask your technical questions on forums or here :
ASP.NET or MVC | C# | Windows Phone
Microsoft Technology Journals by Abhimanyu K Vatsa

22 Oct 2012

HandleErrorAttribute OR Error Handling in MVC 4

HandleErrorAttribute in MVC is used to display friendly error pages to user when something goes wrong in the application. Let’s create a simple exception in the application to explore HandleErrorAttribute.

I have created a demo app using ‘Internet’ template, create the same you too to explore.

Now, open the ‘Home’ controller and throw a new exception from ‘Index’ action:

In above image, I’ve added a simple line to throw an error whenever application reaches to ‘Home’ controller and ‘Index’ action. Now, run the application on localhost and also on production server to view the error.

I’ve deployed the application on my local production server using domain ‘’ to look yellow death screen (error page) closely on production and development servers. If you look at the error pages and compare the results of green rectangular regions, MVC smartly hiding things on production server but this is not enough from user point of view.

Let’s open the ‘Web.config’ file and add <customErrors mode=”On”/>

There are three modes, RemoteOnly is default (above yellow death screen an example of this mode), and by using ‘On/Off’ mode we can switch to custom error page that is available in Views>Shared folder.

Run the application now on both servers (development/localhost & production), you will see the custom error page.

There is a method ‘RegisterGlobalFilters()’ having ‘filters.Add(new HandleErrorAttribute())’ filter that deals with all the errors in MVC application. The method ‘RegisterGlobalFilters()’ called by ‘Application_Start()’ method.

Now, let’s comment ‘filters.Add(new HandleErrorAttribute())’ and run the application on localhost and on production server.

If you run the application, this is what you will see on development server and production server.

You will notice, this is not showing the detailed information of error page like ‘Source Error’, ‘Stack Trace’, and ‘Exception Details’, just says its Runtime error.

Hope this helps. Thanks.
Abhimanyu Kumar Vatsa

No comments:

Post a Comment