Getting Started
Exception is part of development. No one can say that his or her application runs without exceptions. But if it can be handled properly your application will run smoothly. ASP.NET MVC provides various ways to handle exception, here we will discuss one by one in detail. But we cannot say which is the best way to handle exception in ASP.NET MVC, because best practice of code depends on the situation that is suitable to us.
Ways of handling exception
- Action wise or try catch block
All the language that supports .net framework provides try catch block to handle exception, also you can use in action to handle exceptions in ASP.NET MVC. But this is sometimes not suitable as it is not reusable across the action method in 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 exception message. It partially resolves code reusability, because it is applicable (can share error handling logic across all the actions in a controller) for all the action methods in 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 the 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 you to share error handling logic across controllers. As like HandleErrorexception filter, you just need to use controller label as in the below example .
- Using Application_Error method.
Exception handling logic can be written in the Application_Error method of global class to handle exceptions in the application label. It is called handling exception globally.