Error handling is crucial for any application. In Line-of-Business (LOB) ASP.NET applications, error handling can be implemented in multiple ways. Generally, when an application needs to perform data validations on data submitted by end-users, we implement data validations using annotations which is also known as Model validation.
Model validation is limited with the Model class (aka entity class), but our application must be capable to validate code while executing - this is known as exception handling.
Traditionally, most of the programming languages provide try…catch…finally block for exception handling. There is nothing wrong in having a try…catch…finally block for every method in each class of the application, but it is always better to implement a global error or exception handler. By having a centralized exception handling, we can make our code more readable and maintainable.
In ASP.NET MVC applications we have exception action filters. Using this action filter, it is easier for the developer to implement global exception handler. I have already posted on MVC Exception Handling at this link.
In the current article we will implement error handling in ASP.NET Core applications for WEB API. It is important to to have a global exception handler in WEB API so that the API action methods can remain clean, readable and maintainable.
ASP.NET Core provides a built-In middleware for global error handling, but we can also implement custom middleware or even we can write try...catch block for each action method. We will implement error handling with all these methods.