using Microsoft.AspNetCore.Http; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.DirectoryServices.Protocols; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace WIDESEA_Core.Middlewares { public class ExceptionHandlerMiddleware { private readonly RequestDelegate _next; public ExceptionHandlerMiddleware(RequestDelegate next) { _next = next; } /// /// 处理HTTP请求并捕获异常 /// /// HTTP上下文 /// 表示异步操作的任务 /// /// 当请求处理过程中发生异常时,会调用HandleExceptionAsync方法进行处理 /// public async Task Invoke(HttpContext context) { try { await _next(context); } catch (Exception ex) { await HandleExceptionAsync(context, ex); } } /// /// 异步处理异常并写入响应 /// /// HTTP上下文 /// 待处理的异常对象 /// 表示异步操作的任务 private async Task HandleExceptionAsync(HttpContext context, Exception e) { if (e == null) return; await WriteExceptionAsync(context, e).ConfigureAwait(false); } /// /// 异步将异常信息写入HTTP响应 /// /// HTTP上下文对象 /// 发生的异常 /// /// 根据异常类型设置对应的HTTP状态码: /// - UnauthorizedAccessException: 返回401未授权状态码 /// - 其他异常: 返回500内部服务器错误状态码 /// 响应内容为JSON格式的错误信息 /// private static async Task WriteExceptionAsync(HttpContext context, Exception e) { var message = e.Message; switch (e) { case UnauthorizedAccessException: context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; break; default: context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; break; } context.Response.ContentType = "application/json"; await context.Response .WriteAsync(JsonConvert.SerializeObject(WebResponseContent.Instance.Error(message))) .ConfigureAwait(false); } } }