using System.Net; namespace Ds.Module.ResultFilter { public class ExceptionHandlerMiddleware { private readonly RequestDelegate _next; public ExceptionHandlerMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { try { await _next(context); } catch (Exception ex) { await HandleExceptionAsync(context, ex); } } private static Task HandleExceptionAsync(HttpContext context, Exception exception) { context.Response.ContentType = "application/json"; context.Response.StatusCode = (int)HttpStatusCode.OK; DsJsonResult result; if (exception is BusinessException businessException) {// BusinessException处理 result = DsResultTool.Fail(businessException.ErrorCode, businessException.Message); } else { // 其他未处理异常处理 // result = ResultTool.Fail(ResultCode.Fail, exception.Message); result = DsResultTool.Fail(DsResultCode.Fail, "系统异常!"); } return context.Response.WriteAsJsonAsync(result); } } }