使用中间件统一处理.net 6 web应用的异常和错误只需要二步即可,分别是:创建错误处理中间件 和 注册错误处理中间件。具体如下:
1、创建错误处理中间件
using System.Net; using System.Text.Json; namespace Test.WebAPI.Middlewares.ExceptionHandler { /// <summary> /// 全局异常处理中间件 /// </summary> public class ExceptionHandlingMiddleware { private readonly RequestDelegate _next; // 用来处理上下文请求 private readonly ILogger<ExceptionHandlingMiddleware> _logger; //日志 public ExceptionHandlingMiddleware(RequestDelegate next, ILogger<ExceptionHandlingMiddleware> logger) { _next = next; _logger = logger; } public async Task InvokeAsync(HttpContext httpContext) { try { await _next(httpContext); //要么在中间件中处理,要么被传递到下一个中间件中去 } catch (Exception ex) { await HandleExceptionAsync(httpContext, ex); // 捕获异常了 在HandleExceptionAsync中处理 } } //此处统一处理错误异常 private async Task HandleExceptionAsync(HttpContext context, Exception exception) { context.Response.ContentType = "application/json"; // 返回json 类型 var response = context.Response; string message = exception.Message; int id = Convert.ToInt32(DateTime.Now.ToString("ddhhmmss")); switch (exception) { case ApplicationException ex: if (ex.Message.Contains("Invalid token")) { response.StatusCode = (int)HttpStatusCode.Forbidden; break; } response.StatusCode = (int)HttpStatusCode.BadRequest; break; case KeyNotFoundException ex: response.StatusCode = (int)HttpStatusCode.NotFound; break; case ArgumentException ex: response.StatusCode = (int)HttpStatusCode.BadRequest; break; default: response.StatusCode = (int)HttpStatusCode.InternalServerError; message = "程序内部错误[" + id + "],请联系管理员"; break; } EventId eventId = new EventId(id); _logger.LogError(eventId, exception, exception.Message); var result = JsonSerializer.Serialize(new { message = message, result = false, code = response.StatusCode }); await context.Response.WriteAsync(result); return; } } }
2、在Program.cs中注册错误处理中间件
//启用全局错误捕获中间件 app.UseMiddleware<ExceptionHandlingMiddleware>();
最佳解决方案
请输入解决方案