106  
csharp
Поиск  
Always will be ready notify the world about expectations as easy as possible: job change page
Jan 10, 2023

Global Exception Handling in .Net Core 6.0 Web API Application

Автор:
Shubhadeep Chattopadhyay
Источник:
Просмотров:
4783

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.

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.

Похожее
Apr 16, 2022
Author: Matthew MacDonald
Sometimes it’s the little things that count. When .NET 6 dropped this November, a few top-line items grabbed all the attention. I’m talking about C# 10, hot reload, Blazor’s AOT compilation, and some serious inner loop performance improvements. All of...
Aug 15, 2021
.NET has a large number of built in exceptions. However, there maybe times when none of the built exceptions seem adequate for your particular scenario and you will need to create your own custom (AKA “user defined”) exception. This post...
Sep 6, 2023
Author: Kenji Elzerman
To write files with C#, you have to know how to do it. The basics aren’t rocket science. There are a few lines of code you need to know. But writing and reading files with C# is something every beginning...
Dec 1, 2023
Author: MESCIUS inc.
Reporting is a common task in business applications, and for that, ComponentOne includes a specialized FlexReport library that allows you to make complex reports. But sometimes, using specialized tools can be too tricky or not flexible enough. For example, if...
Написать сообщение
Тип
Почта
Имя
*Сообщение
RSS
Если вам понравился этот сайт и вы хотите меня поддержать, вы можете
10 историй, как «валят» айтишников на технических интервью
Функции и хранимые процедуры в PostgreSQL: зачем нужны и как применять в реальных примерах
Soft skills: 18 самых важных навыков, которыми должен владеть каждый работник
Семь итераций наивности или как я полтора года свою дебютную игру писал
Вопросы с собеседований, которые означают не то, что вы думаете
Путеводитель по репликации баз данных
5 приемов увеличения продуктивности разработчика
Топ 8 лучших ресурсов для практики программирования в 2018
Использование SQLite в .NET приложениях
GraphQL решает кучу проблем — рассказываем, за что мы его любим
LinkedIn: Sergey Drozdov
Boosty
Donate to support the project
GitHub account
GitHub profile