Files
QYZH.InteractiveMagazine/QYZH.InteractiveMagazine.Infrastructure/Middleware/GlobalExceptionMiddleware.cs

80 lines
2.5 KiB
C#
Raw Normal View History

2026-06-01 13:42:40 +08:00
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);
2026-06-01 13:42:40 +08:00
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);
}
}