Files
QYZH.InteractiveMagazine/QYZH.InteractiveMagazine.Infrastructure/Middleware/GlobalExceptionMiddleware.cs
glz 0a32754740 refactor: 完成系统基础架构重构与业务逻辑优化
本次提交包含多项核心变更:
1.  **用户体系重构**:将管理员用户状态从字符串改为整型枚举,移除微信用户冗余字段Points和GrowthPoints,新增通用基础实体主键配置
2.  **代码清理**:删除HealthController、WxUserMedal、WxUserBag等废弃文件,移除WeChatDto中冗余查询字段
3.  **响应格式统一**:重构BaseResponse与ResultCode枚举,标准化全局响应格式
4.  **权限与验证优化**:添加JWT认证与开发环境免认证逻辑,新增模型验证过滤器,统一控制器认证配置
5.  **工具与配置更新**:新增dotnet-tools.json配置EF工具,调整Swagger与压缩中间件配置,优化SqlSugar默认值处理逻辑
6.  **业务逻辑简化**:移除AutoMapper映射,改为手动映射DTO以提升性能,修复异常处理与响应返回逻辑
2026-06-02 17:58:10 +08:00

80 lines
2.5 KiB
C#

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;
/// <summary>
/// 全局异常中间件
/// </summary>
public class GlobalExceptionMiddleware : IMiddleware
{
private readonly ILogger<GlobalExceptionMiddleware> _logger;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="logger">日志记录器</param>
public GlobalExceptionMiddleware(ILogger<GlobalExceptionMiddleware> logger)
{
_logger = logger;
}
/// <summary>
/// 执行中间件
/// </summary>
/// <param name="context">HTTP上下文</param>
/// <param name="next">下一个中间件委托</param>
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);
}
}
/// <summary>
/// 处理业务异常
/// </summary>
/// <param name="context">HTTP上下文</param>
/// <param name="ex">业务异常</param>
private static async Task HandleBusinessExceptionAsync(HttpContext context, BusinessException ex)
{
context.Response.ContentType = "application/json";
context.Response.StatusCode = StatusCodes.Status400BadRequest;
var response = BaseResponse<object>.Fail(ResultCode.FAIL,ex.Message);
var json = JsonSerializer.Serialize(response);
await context.Response.WriteAsync(json);
}
/// <summary>
/// 处理系统异常
/// </summary>
/// <param name="context">HTTP上下文</param>
/// <param name="ex">系统异常</param>
private static async Task HandleSystemExceptionAsync(HttpContext context, Exception ex)
{
context.Response.ContentType = "application/json";
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
var response = BaseResponse<object>.Fail("系统内部错误,请稍后重试");
var json = JsonSerializer.Serialize(response);
await context.Response.WriteAsync(json);
}
}