using System.Net; using System.Text.Json; namespace DS.WMS.JobServiceApi { public class ExceptionHandlingMiddleware { private readonly RequestDelegate _next; // 用来处理上下文请求 public ExceptionHandlingMiddleware(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext httpContext) { try { await _next(httpContext); //要么在中间件中处理,要么被传递到下一个中间件中去 } catch (Exception ex) { await HandleExceptionAsync(httpContext, ex); // 捕获异常了 在HandleExceptionAsync中处理 } } private async Task HandleExceptionAsync(HttpContext context, Exception exception) { context.Response.ContentType = "application/json"; // 返回json 类型 var response = context.Response; var errorResponse = new ErrorResponse { Success = false, }; // 自定义的异常错误信息类型 switch (exception) { default: response.StatusCode = (int)HttpStatusCode.InternalServerError; errorResponse.Message = exception.Message;// "Internal Server errors. Check Logs!"; break; } var result = JsonSerializer.Serialize(errorResponse); await context.Response.WriteAsync(result); } private class ErrorResponse { public bool Success { get; set; } = true; public string Message { get; set; } } } }