using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using QYZH.InteractiveMagazine.Models.Common; using QYZH.InteractiveMagazine.Models.Dto; using System.Text.Json; namespace QYZH.InteractiveMagazine.Infrastructure.Middleware; /// /// 全局异常中间件 /// public class GlobalExceptionMiddleware : IMiddleware { private readonly ILogger _logger; /// /// 构造函数 /// /// 日志记录器 public GlobalExceptionMiddleware(ILogger logger) { _logger = logger; } /// /// 执行中间件 /// /// HTTP上下文 /// 下一个中间件委托 public async Task InvokeAsync(HttpContext context, RequestDelegate next) { try { await next(context); } catch (BusinessException ex) { _logger.LogWarning(ex, "业务异常:{Message}", ex.Message); await HandleBusinessExceptionAsync(context, ex); } catch (Exception ex) { _logger.LogError(ex, "系统异常:{Message}", ex.Message); await HandleSystemExceptionAsync(context, ex); } } /// /// 处理业务异常 /// /// HTTP上下文 /// 业务异常 private static async Task HandleBusinessExceptionAsync(HttpContext context, BusinessException ex) { context.Response.ContentType = "application/json"; context.Response.StatusCode = StatusCodes.Status400BadRequest; var response = BaseResponse.Fail(ex.Message, ex.Code); var json = JsonSerializer.Serialize(response); await context.Response.WriteAsync(json); } /// /// 处理系统异常 /// /// HTTP上下文 /// 系统异常 private static async Task HandleSystemExceptionAsync(HttpContext context, Exception ex) { context.Response.ContentType = "application/json"; context.Response.StatusCode = StatusCodes.Status500InternalServerError; var response = BaseResponse.Fail("系统内部错误,请稍后重试"); var json = JsonSerializer.Serialize(response); await context.Response.WriteAsync(json); } }