using LiveForum.Code.Base; using LiveForum.Code.ExceptionExtend; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System; namespace LiveForum.Code.MiddlewareExtend { /// /// 异常中间件 /// 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 (ArgumentNullException ex) { _logger.LogError($"ArgumentNullException异常记录=>{context.Request.Path.ToString()},{ex.Message}", ex); // 如果响应已经开始了,就不能再修改响应头或写入内容 if (context.Response.HasStarted) { return; } context.Response.StatusCode = StatusCodes.Status200OK; BaseResponse baseResponse = new BaseResponse(ResponseCode.ParamError, ex.ParamName ?? "参数错误", null) { }; context.Response.ContentType = "application/json; charset=utf-8"; // 将异常信息写入 HTTP 响应 await context.Response.WriteAsync(baseResponse.ToString()); } catch (Exception ex) { _logger.LogError($"Exception异常记录=>{context.Request.Path.ToString()},{ex.Message}", ex); // 如果响应已经开始了,就不能再修改响应头或写入内容 if (context.Response.HasStarted) { return; } var box = ex as MessageBox; if (box != null) { context.Response.ContentType = "application/json; charset=utf-8"; context.Response.StatusCode = StatusCodes.Status200OK; // 将异常信息写入 HTTP 响应 await context.Response.WriteAsync(box.BaseResponse.ToString()); return; } // 设置 HTTP 响应状态码为 500 context.Response.ContentType = "application/json; charset=utf-8"; context.Response.StatusCode = StatusCodes.Status200OK; BaseResponse baseResponse = new BaseResponse(ResponseCode.Error, ex.Message, null); // 将异常信息写入 HTTP 响应 await context.Response.WriteAsync(baseResponse.ToString()); } finally { } } } }