Introduction
Exception handling deals with undesirable and unaddressed errors that can crash your system; hence, it is one of the crucial processes of any programming language.
In this article, we are going to learn how to implement Global Exception Handling in Asp.Net Core WebAPI.
There are many ways available to implement Global Exception Handling in Asp.Net Core WebApi. In this article, we are going to discuss how to implement Global exceptions using Custom Middleware.
This article can be used by Beginner, Intermediate, and Experienced.
Prerequisite
- Visual Studio 2022
- Understanding of Middleware
- Understanding of CustomMiddleware
Custom Middleware
I hope you have a good understanding of Middleware and CustomMiddelware. If you don't, I recommend that you please read Middleware and CustomMiddleware first and then proceed to read Global Exception Handling in Asp.Net WebApi.
Step 1. Create Asp.Net WebApi project”.
Step 2. Add new Middleware class “ExceptionMiddleware.cs”.
Step 3. Register Middleware in the program.cs file.
Ensure that you either comment out or remove the UseExceptionHandler default middleware, as it could lead to undesirable conflicts. It isn't logical to have several middleware performing the same function, right?
Step 4. Let’s throw an exception from the WeatherForecastController for demo purposes.
We are throwing exceptions from the Get endpoint.
Step 5. Let’s execute and see the output.
You will see the Error message as output.
![Error message]()
This is the best way to implement Global Exception handing in Asp.Net Core 7 Web Api. In the next article, we will explore how to implement global exception handling.
I hope you have learned and enjoyed this article.