Introduction
ASP.NET MVC provides more than one way to handle exceptions in MVC projects. Here in this article, we are going to discuss one by one all the ways in detail.
Getting Started
The exception is part of development no one can say that his or her application runs without exception. But if it can handle properly your application will run softly. ASP.NET MVC provides various ways to handle the exception, here we will discuss one by one in details. But we cannot say which is the best way to handle exception in ASP.NET MVC, because of the best practice of code dependence on the situation that suitable to us.
Ways of handling exception
- Action wise or try-catch block
All the language that support .net framework provides try catch block to handle the exception, same you can use in action to handle exception in ASP.NET MVC. But this is sometimes not suitable as it is not reusable across the action method in the controller.
- Controller wise or overriding OnException in controller.
Exception can be handled by overriding onException function of controller’s base class called ControllerBase. In this function, you can write your own exception handling logic to display the exception messages. It partially resolved code reusability, because it is applicable (can share error handling logic across all the actions in a controller) for all the action methods in the controller.
- Using Exception filter in action method or controller.
ASP.NET MVC provides HandleError attribute (exception filter) to handle exception in ASP.NET MVC, it is built-in filter provided by ASP.NET MVC. The HandleError attribute in ASP.NET MVC can be applied over the action method as well as Controller or at the global level. But it only works when you have enabled the custom errors in web.config.
- Custom errors in web.config.
In the “Web.config” file you need to add the “customErrors” tag and point to the “Error” view as shown in the below “Web.config”. This can be used handle http errors only like file not found and can be customized using above mentioned way as well.
- Custom filter .
ASP.NET MVC provides facility to create your custom filter by inheriting HandleErrorAttribute class provided by it. This enables to share error handling logic across controllers. As like HandleError exception filter, just need to use controller label as like below example . - Using Application_Error method.
Exception handling logic can be written in the Application_Error method of the global class to handle exception in the application label. It is called handling exception globally.