Exception Handling is one of the important topics in Software Development. Exception means mainly run-time errors that occur at the time of execution of your application. The developer needs to handle that exception otherwise the application will be terminated.
Every developer has their own way of handling the errors in their code. Some of them are quite comfortable with having a try-catch block in their code and return system exception message. On the other hand, some developers prefer to return some customized meaningful error messages to their users. So, the basic is to capture the exception and respond with some messages.
Now the question is what is the effective way to implement the exception handling in your code. Let‘s start with an example.
Step 1: Open Visual Studio 2022 and click on “Create a new project”.
Create a new project with Visual Studio 2022
Step 2: Select the project template called “ASP.NET Core Web API” and click on Next.
Select the project template
Step 3: Put your Project Name, Location Path, and Solution Name, and click on Next.
Configure project
Step 4: Make sure the .Net framework version is 6.0 and keep other options as default. Then click on Create to land on the Visual Studio code editor.
Framework selection
Exception Handling with Try-Catch block
Step 5: Let’s start with a try-catch block for exception handling. The basic exception handling approach. Here I am using the default API template called WeatherForecast to demonstrate the functionalities.
Weather Forecast Controller default code
This is the default code snippet that comes by default with the .Net Core Web API project. In postman, it is showing the expected result also.
Postman response with default code
Let’s add a try-catch block in code and create an exception over there.
Controller Code with Try-Catch block
In the controller code, I have added a try-catch block and forcefully threw an exception.
Postman exception response with try-catch block
In the postman, the response is coming from the try-catch block.
Here is a very simple code block to check the try-catch exception handling and it will work fine. But there are some downsides to this approach when dealing with large applications.
Let’s assume you have large amount of controllers in your project and have multiple actions in each controller. Then for exception handling, you need to add a try-catch block to every action in the controller. Sometimes there might be a need to add try-catch to your business logic or services too. Then you will come up with a huge amount of lines of code in your project and which is not good. It will reduce the cleanliness of your code and also looks very clumsy.
So, there is a good approach we have to handle the above problem.
Global Exception Handling using Custom Middleware
Just imagine if you have an option to put exception handling in one place instead of adding try-catch to each controller and action. It will make our life easier right? That’s what Global Exception Handling exactly does. It is a concept to keep in your exception handling at a centralized place and use throughout your application. For that, we need to create a custom middleware in our project and use the following code snippet.
I have added one folder called Middleware in the project root directory and added two classes called ResponseModel.cs and GlobalExceptionHandlingMiddleware.cs.
ResponseModel.cs
GlobalExceptionHandlingMiddleware.cs
In the above code snippet, we have used custom middleware to handle the exception at a centralized place. Here we need to register ILogger and RequestDelegate services through Dependency Injection. The next parameter of the RequestDelegate type is a function delegate that can process our HTTP Requests.
After registering, we have to use the Invoke() method. Otherwise, the RequestDelegate can’t process requests.
Also, we have created a new method called HandleExceptionAsync() for adding our custom logic for exception handling. If there is no exception occurred during the Application runtime then it should generate a successful response. But in case of any exception, it will trigger our middleware catch block and call the HandleExceptionAsync() method. In that method, we just set up the response status code, and content type and return a response.
Just remember one thing all our custom exceptions are derived from the Exception base class.
Now let’s add the middleware to our Program.cs file.
Program.cs
So our global exception handler is ready to use. Now let’s modify our controller methods as below.
WeatherForecastController.cs
Now we do not need any try-catch block here, so removed it. From our code, we will be throwing the exception according to our use case and the middleware will capture and respond with proper error messages.
Let’s test it in the Postman.
Postman response after implementing Global Exception Handling Middleware
Here in the postman, you can see that we are getting the exception response generated by the middleware and for the structured response we have used the response model.
Thanks. Let me know your feedback in the comments section.
Here is the GitHub repository used for the demo, you can clone the source code and play around with it as per your needs.