When we are building our application, although we hope that our application will run without any errors until the end of time. This is not really the case exceptions happens in applications and we need to handle them.

Exception Handling is a foundation that we need to consider while we are designing and building our application to have a stable application and avoid application crashes.

There are many ways to implement exception handling while building our applications from a very granular approach to a more generic way.

In this article we will be exploring global exception handling through middleware to catch runtime errors efficiently as per our requirement


The first thing we need to do is to create a new WebApi application

Now that our application has been created we need to install some packages

To make sure everything is running as it should we need to build our application

Now it’s time to add the models, for this sample application we will be creating an app to list all F1 drivers. For this we will create a Models folder in the root directory of our application which will contain our models

Inside the Models folder we will create a new class called Driver

After the model has been created the next step is to create our database db context in the root directory of our application we will create a new folder called Data and inside the Data folder will add the AppDbContext class

Now we need to add the connection string in the appsettings.json

Next we need to update our program.cs

Once we add these we can do our migration

Now lets create the DriverServices in the root directory of our application let us create a new folder called Services and inside that folder we will create a new interface called IDriverService

Now inside the same folder we will create a new class called DriverService

Let us now update our Program.cs so our DriverServices would be injected in our Dependency Inject container

Now lets create our DriverController, insider the controller folder we will create a new class called DriversController and will add the following

Now let us add a new folder called Exceptions which will be utilised to manage all of our exceptions

We will be adding the following exceptions

Now that our exceptions has been added, we need to add a folder to the root directory of our application called configurations where we can build our GlobalErrorHandlingMiddleware

The GlobalErrorHandlingMiddleware is used to provide more control over exceptions which the application will generate

If there is any errors within an incoming request the GlobalErrorHandlingMiddleware will handle the error

Now lets create ApplicationBuilderExtension so we can inject our middleware inside the Services folder

Now let us inject this in the Program.cs


You have learned about global error handling in .NET 6 Web Api. Hope you enjoy this tutorial.

Leave a comment

Your email address will not be published.