Files

87 lines
2.6 KiB
C#
Raw Permalink Normal View History

2019-12-23 16:32:06 +08:00
using System;
using System.Linq;
2019-12-23 16:32:06 +08:00
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
2020-08-05 15:29:56 +08:00
using SimApi.Communications;
2019-12-23 16:32:06 +08:00
using Microsoft.Extensions.Logging;
using SimApi.Configurations;
2020-08-05 15:29:56 +08:00
using SimApi.Exceptions;
using SimApi.Helpers;
2019-12-23 16:32:06 +08:00
2024-03-23 07:29:43 +08:00
namespace SimApi.Middlewares;
/// <summary>
/// 异常处理中间件
/// </summary>
public class SimApiExceptionMiddleware(
RequestDelegate next,
ILogger<SimApiExceptionMiddleware> log,
SimApiOptions simApiOptions)
2019-12-23 16:32:06 +08:00
{
2024-03-23 07:29:43 +08:00
public async Task InvokeAsync(HttpContext context)
2019-12-23 16:32:06 +08:00
{
2024-03-23 07:29:43 +08:00
if (context.Request.Headers.TryGetValue("Query-Id", out var header))
2019-12-23 16:32:06 +08:00
{
2024-03-23 07:29:43 +08:00
context.Response.Headers["Query-Id"] = header;
2019-12-23 16:32:06 +08:00
}
2024-03-23 07:29:43 +08:00
try
2019-12-23 16:32:06 +08:00
{
2024-03-23 07:29:43 +08:00
await next(context);
2025-11-03 21:41:35 +08:00
if (!context.Response.HasStarted)
2020-08-29 11:49:44 +08:00
{
SimApiError.ErrorWhenFalse(
simApiOptions.SimApiExceptionOptions.SkipStatusCodes.Contains(context.Response.StatusCode),
context.Response.StatusCode);
2019-12-23 16:32:06 +08:00
}
}
2024-03-23 07:29:43 +08:00
catch (Exception ex)
{
2026-04-14 13:38:19 +08:00
// 解包异步异常
ex = UnwrapAggregateException(ex);
SimApiBaseResponse response;
if (ex is SimApiException simEx)
{
response = string.IsNullOrEmpty(simEx.Message)
? new SimApiBaseResponse(simEx.Code)
: new SimApiBaseResponse(simEx.Code, simEx.Message);
2026-05-20 09:38:40 +08:00
if (context.Response.StatusCode == 404)
{
response.Message = "接口不存在";
}
2026-04-14 13:38:19 +08:00
}
else
{
2026-05-20 09:38:40 +08:00
log.LogError(ex, ex.Message);
response = new SimApiBaseResponse(500);
2026-04-14 13:38:19 +08:00
}
await ErrorResponseAsync(context, response);
2024-03-23 07:29:43 +08:00
}
}
2026-04-14 13:38:19 +08:00
private static Exception UnwrapAggregateException(Exception ex)
2024-03-23 07:29:43 +08:00
{
2026-04-14 13:38:19 +08:00
while (ex is AggregateException aggEx && aggEx.InnerException != null)
{
ex = aggEx.InnerException;
}
return ex;
}
/// <summary>
/// 异步输出错误响应(修复异步异常捕获核心)
/// </summary>
private static async Task ErrorResponseAsync(HttpContext context, SimApiBaseResponse response)
{
// 响应已开始则直接返回,不修改
if (context.Response.HasStarted)
return;
2024-04-23 12:27:36 +08:00
context.Response.StatusCode = 200;
2026-04-14 13:38:19 +08:00
context.Response.ContentType = "application/json";
context.Response.ContentLength = null; // 清除可能已设置的 Content-Length
2026-04-14 13:38:19 +08:00
await context.Response.WriteAsync(response.ToString());
2019-12-23 16:32:06 +08:00
}
}