using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; using System; using System.Text.Json; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Logging; using Utility.Entity; using Newtonsoft.Json; namespace Utility { public class CustomerExceptionMiddleware { private readonly RequestDelegate _next; private readonly ILogger _logger; public CustomerExceptionMiddleware(RequestDelegate next, ILogger logger) { _next = next; _logger = logger; } public async Task Invoke(HttpContext context) { try { await _next(context); } catch (Exception ex) { _logger.LogError(ex, ex.Message); context.Response.ContentType = "application/json"; context.Response.StatusCode = StatusCodes.Status500InternalServerError; var result = "系统异常,请联系管理员"; if (ex is AppFriendlyException) result = ex.Message; var apiResponse = new ApiResponse( code: (int)ResponseEnum.Error, message: result, data: result ); await context.Response.WriteAsync(JsonConvert.SerializeObject(apiResponse)); } } } /// /// 静态类 /// public static class ExceptionMiddlewareExtension { /// /// 静态方法 /// /// 要进行扩展的类型 public static void UseExceptionMiddleware(this IApplicationBuilder app) { app.UseMiddleware(typeof(CustomerExceptionMiddleware)); } } }