Site icon Dotnet Helpers

Error Handling in ASP.Net MVC Using HandleError Attribute

Exception handling plays an important role in any application, whether it is a web application or a Windows Forms application.Implementing a proper exception handling in our application is important. In most scenario, after we caughtthe exception, we have to log the exception details or show a friendly message to the user. ASP.NET MVC provides built-in features for exception handling through exception filters. The HandleError is the default built-in exception filter which is used to handle the exception. In this post, we are going to discuss about the HandleError filter.

What HandleError filter do?

ASP.Net MVC HandleError attribute provides a built-in exception filter. The HandleError attribute in ASP.NET MVC can be applied over the action method as well as a controller or at the global level for handle the exception in controller and action level. While creating our application, the HandleError attribute is automatically included within the Global.asax.cs and registered in FilterConfig.cs as shown below.

It can applied at the global level as well. The HandleError attribute is the default implementation of IExceptionFilter. The HandleError filter handles the exceptions which been raised at the controller/actions. Then it return a custom error view. Let we discuss detail about with example.

Limitation of HandleError Filter:

Properties in HandleError Attribute

The HandleError Error attribute has a few properties for handling the exception.

ExceptionType: It is used to specify the type of exception to be catch. If this property is not set then it will handles all type exceptions.

TypeId: Set the unique identifier for this attribute

View: Need to specify the name of view. It will redirect to particular view when exception occur.

Master: Master View for displaying the exception.

Example:

Used Version Detail : Visual studio 2013, Version 4.5, MVC 5

While creating ASP.NET MVC application the error.cshtml view is created automatically under the shared folder. Creating our own CustomError.cshtml view for displaying error with custom content for the user.

Controller:

HandleErrorAttribute controller has an index action method. From the below code, When the NullReferenceException error happens in the action Index, then the ASP.NET MVC HandleError attribute will find in a view called “CustomError”, in the shared folder and renders it to the user. (Placing in the “Shared” Folder, will be shared with all controllers).

Sample Attribute :

  1. [HandleError(ExceptionType = typeof(System.Data.DataException), View = “DatabaseError”)]
  2. [HandleError(ExceptionType = typeof(NullReferenceException), View = “NullReferenceError”)]

Web.config

The HandleError filter works only if the <customErrors> section is turned on in web.config.

Output :

Note:

 

Exit mobile version