using System; using System.Net; using System.Threading.Tasks; using GxPress.Common.Exceptions; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Newtonsoft.Json; namespace GxPress.Common.Middleware { /// /// 自定义异常中间件 /// 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.Invoke(context); } catch (BusinessException be) { _logger.LogDebug(be.Message); await HandleBusinessException(context, be); } catch (System.Exception ex) { _logger.LogError(ex, ex.Message); await HandleSystemException(context, ex); } } /// /// 处理业务异常 /// /// /// /// private Task HandleBusinessException(HttpContext context, BusinessException be) { context.Response.StatusCode = (int)HttpStatusCode.BadRequest; context.Response.ContentType = "application/json;charset=utf-8"; return context.Response.WriteAsync(JsonConvert.SerializeObject(new { be.Message, be.StackTrace })); } /// /// 处理系统异常 /// /// /// /// private Task HandleSystemException(HttpContext context, Exception ex) { context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; context.Response.ContentType = "application/json;charset=utf-8"; return context.Response.WriteAsync(JsonConvert.SerializeObject(ex)); } } }