.Net Core WebApi 3.1 增加全局错误处理

在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;

        /// 
        /// 任务调用
        /// 
        /// http请求
        /// 
        public async Task Invoke(HttpContext context)
        {            
            try
            {                
                await _next(context);
            }
            catch (Exception ex)
            {
                await HandleExceptionAsync(context, ex);
            }
        }

        /// 
        /// 统一处理错误
        /// 
        /// http请求
        /// 错误信息
        /// post请求的参数值
        /// 
        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));
使用统一错误处理

你可能感兴趣的:(.Net Core WebApi 3.1 增加全局错误处理)