• .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

      

  • 相关阅读:
    Android Studio 或 IntelliJ IDEA获取数字签名的方法
    android四大组件学习总结以及各个组件示例(2)
    android四大组件学习总结以及各个组件示例(1)
    Android利用canvas画画板
    Android service 服务的应用之电话监听器以及短信监听器
    Android Gesture 手势创建以及使用示例
    安卓http源码查看器详解
    java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
    二叉树的非递归遍历(栈)
    python 游戏(滑动拼图Slide_Puzzle)
  • 原文地址:https://www.cnblogs.com/shenghuotaiai/p/13613536.html
Copyright © 2020-2023  润新知