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.
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
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:
- It catch only 500 Http error and not catch HTTP errors like 404,401 ..
- It has no support to log the exceptions. We can log the exception by create custom error filter by implementing
- It doesn’t catch the errors that occur outside the controllers and also not catch the ajax calls error too.
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.
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.
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).
public class HandleErrorAttributeController : Controller
[HandleError(View = "CustomError")]
public ActionResult Index()
throw new NullReferenceException();
Sample Attribute :
- [HandleError(ExceptionType = typeof(System.Data.DataException), View = “DatabaseError”)]
- [HandleError(ExceptionType = typeof(NullReferenceException), View = “NullReferenceError”)]
The HandleError filter works only if the <customErrors> section is turned on in web.config.
<span style="color: #000000;"><system.web>
- The HandleError filter works only if the <customErrors> section is turned on in web.config.
- We can use HandleError Attribute for the entire application by registering it as a global error handler.