.NetCore 3.1 全局异常捕获 API

 创建自定义的中间件来实现我们的自定义异常处理

1 、CustomExceptionMiddleware

 public class CustomExceptionMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<CustomExceptionMiddleware> _logger;
        public CustomExceptionMiddleware(RequestDelegate next, ILogger<CustomExceptionMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception e)
            {
                await ExceptionHandlerAsync(context, e);
            }
        }

        private async Task ExceptionHandlerAsync(HttpContext context, Exception ex)
        {
            context.Response.ContentType = "application/json";
            context.Response.StatusCode = StatusCodes.Status200OK;
            _logger.LogError($"系统出现错误:{ex.Message}--{ex.StackTrace}");

            var result = new ResultObject(500, ex.Message);

            await context.Response.WriteAsync(JsonConvert.SerializeObject(result));
        }
    }

    // Extension method used to add the middleware to the HTTP request pipeline.
    public static class CustomExceptionMiddlewareExtensions
    {
        public static IApplicationBuilder UseCustomExceptionMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<CustomExceptionMiddleware>();
        }
    }

2、Configure

 //全局异常日志
 app.UseMiddleware<CustomExceptionMiddleware>();

第二种

.NET Core 给我们提供了一种处理全局异常的方式,只需要稍加修改,就可以使用内置且完善的的中间件。我们需要做的修改就是在 Startup 类中修改 Configure方法:

// 全局异常捕获
            app.UseExceptionHandler(errors =>
            {
                errors.Run(async context =>
                {
                    var feature = context.Features.Get<IExceptionHandlerPathFeature>();
                    var error = feature?.Error;
                    var result = new ResultObject(500, error.Message);
                    if (error != null)
                    {
                        _logger.LogError($"系统出现错误:{error.Message}-{error.StackTrace}");
                    }

                    context.Response.StatusCode = StatusCodes.Status200OK;
                    context.Response.ContentType = "application/json";
                    await context.Response.WriteAsync(JsonConvert.SerializeObject(result));
                });
            });

  

API请求日志记录

1、ApiLogFilter

public class ApiLogFilter : IAsyncActionFilter
    {
        private readonly ILogger logger;

        public ApiLogFilter(ILogger<ApiLogFilter> logger)
        {
            this.logger = logger;
        }

        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            string actionArguments = context.ActionArguments.ToJson();

            var resultContext = await next();

            string url = resultContext.HttpContext.Request.Host + resultContext.HttpContext.Request.Path + resultContext.HttpContext.Request.QueryString;

            string method = resultContext.HttpContext.Request.Method;

            dynamic result = resultContext.Result.GetType().Name == "EmptyResult" ? new { Value = "EmptyResult" } : resultContext.Result as dynamic;

            string response = JsonConvert.SerializeObject(result.Value);

            logger.LogInformation($"URL:{url} 
 " +
                                  $"Method:{method} 
 " +
                                  $"ActionArguments:{actionArguments}
 " +
                                  $"Response:{response}
 ");
        }
    }

2、Startup ConfigureServices

services.AddMvc(options =>
    {
        options.Filters.Add(typeof(ApiLogFilter));
    });

  

转载记录:https://www.cnblogs.com/xiangxiufei/p/13337926.html

  

原文地址:https://www.cnblogs.com/shenghuotaiai/p/13613536.html