using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Infrastructure.Api.Middwares { public class ExceptionMiddleware { private readonly RequestDelegate _next; private readonly ILogger _logger; public ExceptionMiddleware(RequestDelegate next, ILogger logger) { _next = next; _logger = logger; } public async Task Invoke(HttpContext context) { try { await _next(context); } catch (Exception e) { await ExceptionHandlerAsync(context, e); } } private async Task ExceptionHandlerAsync(HttpContext context, Exception ex) { context.Response.ContentType = "application/json"; context.Response.StatusCode = StatusCodes.Status200OK; _logger?.LogError($"系统出现错误:{ex.Message}--{ex.StackTrace}"); var result = new CommonResponse { Code = context.Response.StatusCode.ToString(), Success = false, Message = ex.Message }; await context.Response.WriteAsync(JsonConvert.SerializeObject(result)); } } }