背景:
全局异常捕获是我们开发当中不可获取的一个环节,顾名思义就是全局的捕获异常,并响应出去,今天就带着各位朋友们在.Net 6.0当中如何做到全局异常捕获.
思路:
我们可以通过请求管道达到我们全局的一个场景,所以我们第一步就是在请求管道中自定义一个全局异常捕获的中间件,并通过try catch来实现,是不是特别简单,好话不多说下面就带着各位步入正题!!!.
实现:
1.在根目录中创建Middlewares文件夹,并创建ExceptionHandlingMiddleware类(自定义中间件)

2.创建一个捕获异常后需要将错误信息响应出去的容器,哈哈哈大白话来说就是一个类,我这就暂命名为ActionTResult

3.实现ExceptionHandlingMiddleware中代码逻辑,不卖关子,直接上代码!!!
1 /// <summary>
2 /// 全局异常捕获中间件
3 /// </summary>
4 public class ExceptionHandlingMiddleware
5 {
6 private readonly RequestDelegate _next; // 用来处理上下文请求
7 private readonly ILogger<ExceptionHandlingMiddleware> _logger;
8
9 public ExceptionHandlingMiddleware(RequestDelegate next, ILogger<ExceptionHandlingMiddleware> logger)
10 {
11 _next = next;
12 _logger = logger;
13 }
14
15 /// <summary>
16 /// 执行中间件
17 /// </summary>
18 /// <param name="httpContext"></param>
19 /// <returns></returns>
20 public async Task InvokeAsync(HttpContext httpContext)
21 {
22 try
23 {
24 await _next(httpContext); //要么在中间件中处理,要么被传递到下一个中间件中去
25 }
26 catch (Exception ex)
27 {
28 await HandleExceptionAsync(httpContext, ex); // 捕获异常了 在HandleExceptionAsync中处理
29 }
30 }
31
32 /// <summary>
33 /// 异步处理异常
34 /// </summary>
35 /// <param name="context"></param>
36 /// <param name="exception"></param>
37 /// <returns></returns>
38 private async Task HandleExceptionAsync(HttpContext context, Exception exception)
39 {
40 context.Response.ContentType = "application/json"; // 返回json 类型
41 var response = context.Response;
42 var errorResponse = new ActionTResult
43 {
44 Succes = SuccessTypeEnum.Error
45 }; // 自定义的异常错误信息类型
46 switch (exception)
47 {
48 case ApplicationException ex:
49 if (ex.Message.Contains("Invalid token"))
50 {
51 response.StatusCode = (int)HttpStatusCode.Forbidden;
52 errorResponse.ErrorMsg = ex.Message;
53 break;
54 }
55 response.StatusCode = (int)HttpStatusCode.BadRequest;
56 errorResponse.ErrorMsg = ex.Message;
57 break;
58 case KeyNotFoundException ex:
59 response.StatusCode = (int)HttpStatusCode.NotFound;
60 errorResponse.ErrorMsg = ex.Message;
61 break;
62 default:
63 response.StatusCode = (int)HttpStatusCode.InternalServerError;
64 errorResponse.ErrorMsg = "Internal Server errors. Check Logs!";
65 break;
66 }
67 _logger.LogError(exception.Message);
68 var result = JsonSerializer.Serialize(errorResponse);
69 await context.Response.WriteAsync(result);
70 }
71 }
4.在请求管道中直接使用即可
1 app.UseMiddleware<ExceptionHandlingMiddleware>();
效果:
到这里其实我们已经实现了一个全局异常捕获了,我们一起来看看效果吧!



在这里本章节就结束了,希望对正在阅读的各位有所帮助,当然如果有发现不足或者不对的地方也欢迎探讨,及时指正!!!