Various ways of exception handling in MVC


Introduction

ASP.NET MVC provides more than one ways to handle exception in MVC projects. Here in this article we are going to discuss one by one all the ways in details.

Getting Started

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 exception, here we will discuss one by one in details. But we cannot say which is best way to handle exception in ASP.NET MVC, because best practice of code dependence the situation that suitable to us.




Ways of handling exception
  1. Action wise or try catch block
    All the language that support .net framework provides try catch block to handle exception, same you can use in action to handle exception in ASP.NET MVC. But this is some time not suitable as it is not reusable across the action method in controller.
  2. 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 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 controller.
  3. 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.
  4. 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 customize using above mentioned way as well.
  5. 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 .
  6. Using Application_Error method.
    Exception handling logic can be written in the Application_Error method of global class to handle exception in the application label. It is called handling exception globally.
Thanks