在api项目下新建类(CustomErrorHandler.cs), 编辑内容如下
using L.UtilityTool.ApiModule;
using L.UtilityTool.Helper;
using L.UtilityTool.RequestModule;
using Microsoft.AspNetCore.Http;
using System;
using System.Threading.Tasks;
namespace SystemApi
{
public class CustomErrorHandler
{
private readonly RequestDelegate _next;
public CustomErrorHandler(RequestDelegate next) => this._next = next;
/// <summary>
/// 任务调用
/// </summary>
/// <param name="context">http请求</param>
/// <returns></returns>
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
/// <summary>
/// 统一处理错误
/// </summary>
/// <param name="context">http请求</param>
/// <param name="exception">错误信息</param>
/// <param name="postValue">post请求的参数值</param>
/// <returns></returns>
private static Task HandleExceptionAsync(HttpContext context, Exception exception)
{
// 请求数据
RequestInfo requestInfo = new RequestInfo(context);
// 回调给客户端的信息
ApiReturnInfo returnInfo = ApiReturn.Error(requestInfo.RequestID);
//// 启用Rabbit MQ记录日志
//if (HelperSettingConfig.GetInstance().GetIsOpenWebApiRabbitMQ())
//{
// // 发送Rabbit MQ错误日志信息
// HelperRabbitMQ.GetInstance().SendMessage(new RabbitMQMessage(ERabbitMQType.SystemErrorLog, returnInfo.Message, requestInfo.RequestID, requestInfo.ClientIP, true, requestInfo, new KeyValue(Copywriting.Error_Message, exception.ToString())));
//}
// 返回给客户端的错误消息
context.Response.ContentType = "application/json";
return context.Response.WriteAsync(HelperJson.SerializeJSON(returnInfo));
}
}
}
在StartUp.cs中增加使用
// 配置错误处理中间件
app.UseMiddleware(typeof(CustomErrorHandler));