Files
simapi-net/Middlewares/SimApiExceptionMiddleware.cs
T

69 lines
2.1 KiB
C#
Raw Normal View History

2019-12-23 16:32:06 +08:00
using System;
2024-12-23 20:26:21 +08:00
using System.IO;
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;
2020-08-05 15:29:56 +08:00
using SimApi.Exceptions;
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)
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
SimApiBaseResponse response;
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
{
2025-11-03 21:41:35 +08:00
switch (context.Response.StatusCode)
{
case 200:
case 301:
case 302:
break;
case 404:
throw new SimApiException(context.Response.StatusCode, "请求的接口不存在");
default:
throw new SimApiException(context.Response.StatusCode);
}
2019-12-23 16:32:06 +08:00
}
}
2024-03-23 07:29:43 +08:00
catch (SimApiException ex)
2019-12-23 16:32:06 +08:00
{
2024-03-23 07:29:43 +08:00
response = string.IsNullOrEmpty(ex.Message)
? new SimApiBaseResponse(ex.Code)
: new SimApiBaseResponse(ex.Code, ex.Message);
ErrorResponse(context, response);
}
catch (Exception ex)
{
2024-04-23 12:27:36 +08:00
log.LogError("{Msg}", ex.Message);
log.LogError("{Msg}", ex.StackTrace);
2024-03-23 07:29:43 +08:00
response = new SimApiBaseResponse(500, ex.Message);
ErrorResponse(context, response);
}
}
/// <summary>
/// 异常抛出错误
/// </summary>
/// <param name="context"></param>
/// <param name="response"></param>
2024-04-23 12:27:36 +08:00
private static void ErrorResponse(HttpContext context, SimApiBaseResponse response)
2024-03-23 07:29:43 +08:00
{
2024-04-23 12:27:36 +08:00
context.Response.StatusCode = 200;
context.Response.Headers.Append("Content-Type", "application/json");
2024-12-23 20:26:21 +08:00
context.Response.WriteAsync(response.ToString()).Wait();
2019-12-23 16:32:06 +08:00
}
}