using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Utility.Entity; namespace Utility { public class CustomerExceptionFilter : IAsyncExceptionFilter { /// /// 重写OnExceptionAsync方法,定义自己的处理逻辑 /// /// /// private readonly ILogger _logger; public CustomerExceptionFilter(ILogger logger) { _logger = logger; } public Task OnExceptionAsync(ExceptionContext context) { // 如果异常没有被处理则进行处理 if (context.ExceptionHandled == false) { //var result = "系统异常,请联系管理员"; //if (context.Exception is AppFriendlyException) var result = context.Exception.Message; var apiResponse = new ApiResponse( code: (int)ResponseEnum.Fail, message: result, data: result ); _logger.LogError(context.Exception, context.Exception.Message); context.Result = new ContentResult { // 返回状态码设置为200,表示成功 StatusCode = StatusCodes.Status200OK, // 设置返回格式 ContentType = "application/json;charset=utf-8", Content = JsonConvert.SerializeObject(apiResponse) }; } // 设置为true,表示异常已经被处理了 context.ExceptionHandled = true; return Task.CompletedTask; } } }