Thứ Ba, 24 tháng 12, 2019

Global Error Handling in ASP.NET Core Web API

Dùng Middleware để xử lý lỗi  ASP.NET Core Web API.
Nguồn  :https://code-maze.com/global-error-handling-aspnetcore/
In this article, we are going to talk about:

Error Handling with Try-Catch Block

To start off with this example, let’s open the Values Controller from the starting project (Global-Error-Handling-Start project). In this project, we can find a single Get() method and an injected Logger service.
It is a common practice to include the log messages while handling errors, therefore we have created the LoggerManager service. It logs all the messages to the C drive, but you can change that by modifying the path in the nlog.config file. For more information about how to use Nlog in .NET Core, you can visit Logging with NLog.
Now, let’s modify our action method to return a result and log some messages:

When we send a request at this endpoint, we will get this result:
Basic request - Global Error Handling
And the log messages:
log basic request - Global Error Handling
We see that everything is working as expected.
Now let’s modify our code, right below the GetAllStudents() method call, to force an exception:
Now, if we send a request:
try catche error - Global Error Handling
And the log messages:

log try catch error
So, this works just fine. But the downside of this approach is that we need to repeat our try-catch blocks in all the actions in which we want to catch unhandled exceptions. Well, there is a better approach to do that.

Handling Errors Globally with the Built-In Middleware

The UseExceptionHandler middleware is a built-in middleware that we can use to handle exceptions. So, let’s dive into the code to see this middleware in action.
First, we are going to add a new class ErrorDetails in the Models folder:
We are going to use this class for the details of our error message.
To continue, let’s create a new folder Extensions and a new static class ExceptionMiddlewareExtensions.cs inside it.
Now, we need to modify it:
In the code above, we’ve created an extension method in which we’ve registered the UseExceptionHandler middleware. Then, we’ve populated the status code and the content type of our response, logged the error message, and finally returned the response with the custom created object.
To be able to use this extension method, let’s modify the Configure method inside the Startup class:

Finally, let’s remove the try-catch block from our code:
And there you go. Our action method is much cleaner now and what’s more important we can reuse this functionality to write more readable actions in the future.
So let’s inspect the result:
Global Handler Middleware
And the log messages:
log global handler middleware
Excellent.
Now, we are going to use a custom middleware for global error handling.

Handling Errors Globally with the Custom Middleware

Let’s create a new folder named CustomExceptionMiddleware and a class ExceptionMiddleware.cs inside it.
We are going to modify that class:
The first thing we need to do is to register our IloggerManager service and RequestDelegate through the dependency injection. The _next parameter of RequestDeleagate type is a function delegate which can process our HTTP requests.
After the registration process, we need to create the InvokeAsync() method. RequestDelegate can’t process requests without it.
If everything goes well, the _next delegate should process the request and the Get action from our controller should generate the successful response. But if a request is unsuccessful (and it is, because we are forcing exception), our middleware will trigger the 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.
Now let’s modify our ExceptionMiddlewareExtensions class with another static method:
Finally, let’s use this method in the Configure method in the Startup class:

Great.
Now let’s inspect the result again:
custom handler middleware

There we go. Our custom middleware is implemented in a couple of steps.