Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Net 6 how to implement global exception handling in developing TodoList applications

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article shows you how to achieve global exception handling in the development of TodoList applications in NET 6. The content is concise and easy to understand, which will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

Demand

Because a variety of domain or system exceptions are thrown in the project, a complete try-catch capture is required in Controller and the return value is repackaged according to whether there are any exceptions. This is a mechanical and tedious work. Is there any way for the framework to do this on its own?

Yes, the name of the solution is global exception handling, or how to make the interface fail gracefully.

target

We want to put exception handling and message return into the framework for unified handling, getting rid of the try-catch block in the Controller layer.

Principles and ideas

Generally speaking, there are two ways to implement global exception handling, but the starting point is through the pipe middleware Middleware Pipeline of .NET Web API. The first way is through .NET built-in middleware; the second is completely custom middleware implementation.

We will briefly introduce how to implement it through built-in middleware, and then actually use the second way to implement our code, we can compare the similarities and differences.

Create a Models folder and an ErrorResponse class in the Api project.

ErrorResponse.cs

Using System.Net;using System.Text.Json;namespace TodoList.Api.Models;public class ErrorResponse {public HttpStatusCode StatusCode {get; set;} = HttpStatusCode.InternalServerError; public string Message {get; set;} = "An unexpected error occurred."; public string ToJsonString () = > JsonSerializer.Serialize (this);}

Create an Extensions folder and create a new static class ExceptionMiddlewareExtensions to implement a static extension method:

ExceptionMiddlewareExtensions.cs

Using System.Net;using Microsoft.AspNetCore.Diagnostics;using TodoList.Api.Models;namespace TodoList.Api.Extensions;public static class ExceptionMiddlewareExtensions {public static void UseGlobalExceptionHandler (this WebApplication app) {app.UseExceptionHandler (appError = > {appError.Run (async context = > {context.Response.ContentType = "application/json"; var errorFeature = context.Features.Get () If (errorFeature! = null) {await context.Response.WriteAsync (new ErrorResponse {StatusCode = (HttpStatusCode) context.Response.StatusCode, Message = errorFeature.Error.Message}. ToJsonString ());}}) );}}

At the beginning of the middleware configuration, note that the middleware pipeline is in order, and putting the global exception handling to the first step (and the last step of the request return) ensures that it can intercept all possible exceptions. This is the position:

Var app = builder.Build (); app.UseGlobalExceptionHandler ()

You can implement global exception handling. Next we look at how to completely customize a global exception handling middleware, in fact, the principle is exactly the same, but I prefer the custom middleware code organization, more concise and clear at a glance.

At the same time, we want to uniformly wrap the return value in format, so we define this return type:

ApiResponse.cs

Using System.Text.Json;namespace TodoList.Api.Models;public class ApiResponse {public T Data {get; set;} public bool Succeeded {get; set;} public string Message {get; set;} public static ApiResponse Fail (string errorMessage) = > new () {Succeeded = false, Message = errorMessage}; public static ApiResponse Success (T data) = > new () {Succeeded = true, Data = data}; public string ToJsonString () = > JsonSerializer.Serialize (this);} implementation

Create a new Middlewares folder and a new middleware GlobalExceptionMiddleware in the Api project

GlobalExceptionMiddleware.cs

Using System.Net;using TodoList.Api.Models;namespace TodoList.Api.Middlewares;public class GlobalExceptionMiddleware {private readonly RequestDelegate _ next; public GlobalExceptionMiddleware (RequestDelegate next) {_ next = next;} public async Task InvokeAsync (HttpContext context) {try {await _ next (context) } catch (Exception exception) {/ / you can log await HandleExceptionAsync (context, exception) here;}} private async Task HandleExceptionAsync (HttpContext context, Exception exception) {context.Response.ContentType = "application/json" Context.Response.StatusCode = exception switch {ApplicationException = > (int) HttpStatusCode.BadRequest, KeyNotFoundException = > (int) HttpStatusCode.NotFound, _ = > (int) HttpStatusCode.InternalServerError}; var responseModel = ApiResponse.Fail (exception.Message); await context.Response.WriteAsync (responseModel.ToJsonString ());}}

So our ExceptionMiddlewareExtensions can be written as follows:

ExceptionMiddlewareExtensions.cs

Using TodoList.Api.Middlewares;namespace TodoList.Api.Extensions;public static class ExceptionMiddlewareExtensions {public static WebApplication UseGlobalExceptionHandler (this WebApplication app) {app.UseMiddleware (); return app;}} verification

First, we need to wrap our return value in Controller, give an example of CreateTodoList, and other similar modifications:

TodoListController.cs

[HttpPost] public async Task Create ([FromBody] CreateTodoListCommand command) {return ApiResponse.Success (await _ mediator.Send (command));}

Remember that we have a Colour attribute on the domain entity of TodoList, which is a value object, and in the process of assignment we gave it a chance to throw a UnsupportedColourException, and we used this domain exception to verify the global exception handling.

In order to verify the need, we can make some modifications to CreateTodoListCommand to accept a string of Colour, as follows:

CreateTodoListCommand.cs

Public class CreateTodoListCommand: IRequest {public string? Title {get; set;} public string? Colour {get; set;}} / / the following code is located in the corresponding Handler, omitting other... var entity = new Domain.Entities.TodoList {Title = request.Title, Colour = Colour.From (request.Colour?? String.Empty)}

To start the Api project, we tried to create a TodoList with an unsupported color:

Request

Response

By the way, check to see whether the normal return format is returned as we expected. Here is the API that requests all TodoList collections to return:

You can see that the normal and abnormal return types have been unified.

In fact, there is another way to achieve global exception handling through Filter, the specific method can refer to this article: Filters in ASP.NET Core, the reason why we do not choose Filter and use Middleware is mainly based on simple, easy to understand, and as the first middleware pipeline middleware to join, effectively covering all component processes, including middleware. The location of the Filter is called after the role of the routing middleware. In practical use, both methods are applied.

The above content is how to implement global exception handling in .NET 6 development of TodoList applications. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report