GitHub profile
.NET Framework .NET C# VB.NET LINQ ASP.NET Web API REST SignalR Windows Forms WPF WCF RabbitMQ PHP SQL Server MySQL PostgreSQL MariaDB SQLite MongoDB ADO.NET ORM Entity Framework Dapper XML JSON HTML5 CSS3 Bootstrap JavaScript jQuery Angular React TypeScript NPM Blazor UI/UX Responsive Web Design Redis Elasticsearch GraphQL Grafana Agile Scrum Kanban Windows Server IIS PowerShell Active Directory TFS Azure Automation Software Reverse Engineering Performance Optimization Git Jira/Confluence CI/CD TeamCity SOLID KISS DRY YAGNI
Always will be ready notify the world about expectations as easy as possible: job change page

Global Exception Handling in .Net Core 6.0 Web API Application

Created: Jan 10, 2023
Author: Shubhadeep Chattopadhyay
Views: 62

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.

 Global Exception Handling in .Net Core Web API

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.



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.


So our global exception handler is ready to use. Now let’s modify our controller methods as below.


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.

Nov 16, 2022
Author: Vipin Sharma
Need to communicate with multiple DBs in one application??Usually we don’t face such scenarios. However if such requirement comes in picture, we will see how easy it is to communicate with multiple DBs using repository pattern in .Net Core Web...
Feb 3, 2022
Author: Satish Chandra Gupta
What if programming languages were stocks? And you had to make a portfolio to fetch good returns in 2022?You probably have seen various surveys and analyses listing the most popular programming languages. Those cover the universe of programming languages, like...
Jan 16, 2023
C# AngleSharp tutorial shows how to parse HTML in C# with AngleSharp library.The library can also parse SVG, MathML, or XML.AngleSharp GitHub: Object Model (DOM) is a standard tree structure, where each node contains one of the components from...
18 января 2023 г.
Автор: Savindu Bandara
What is paginationSo you may have already used this one, but you may be wondering what this pagination 😀. So as in figure 1, pagination helps you break a large number of datasets into smaller pages. For example, a storybook...
Send message
Your name

© 1999–2023 WebDynamics
1980–... Sergey Drozdov
Area of interests: .NET | .NET Core | C# | ASP.NET | Windows Forms | WPF | Windows Phone | HTML5 | CSS3 | jQuery | AJAX | MS SQL Server | Transact-SQL | ADO.NET | Entity Framework | IIS | OOP | OOA | OOD | WCF | WPF | MSMQ | MVC | MVP | MVVM | Design Patterns | Enterprise Architecture | Scrum | Kanban