using System; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using SimApi.Communications; using Microsoft.Extensions.Logging; using SimApi.Exceptions; namespace SimApi.Middlewares { /// /// 异常处理中间件 /// public class SimApiExceptionMiddleware { private RequestDelegate Next { get; } private ILogger Log { get; } public SimApiExceptionMiddleware(RequestDelegate next, ILogger log) { Log = log; Next = next; } public async Task InvokeAsync(HttpContext context) { if (context.Request.Headers.ContainsKey("Query-Id")) { context.Response.Headers["Query-Id"] = context.Request.Headers["Query-Id"]; } var response = new SimApiBaseResponse(); try { await Next(context); if (context.Response.StatusCode != 200) { if (!new[] { 301, 302 }.Contains(context.Response.StatusCode)) { throw new SimApiException(context.Response.StatusCode); } } } catch (SimApiException ex) { response = string.IsNullOrEmpty(ex.Message) ? new SimApiBaseResponse(ex.Code) : new SimApiBaseResponse(ex.Code, ex.Message); ErrorResponse(context, response); } catch (Exception ex) { Log.LogError(ex.Message); Log.LogError(ex.StackTrace); response = new SimApiBaseResponse(500, ex.Message); ErrorResponse(context, response); } } /// /// 异常抛出错误 /// /// /// private void ErrorResponse(HttpContext context, SimApiBaseResponse response) { if (!context.Response.HasStarted) { context.Response.StatusCode = 200; context.Response.Headers.Add("Content-Type", "application/json"); context.Response.WriteAsync(response.ToString()); } } } }