zoukankan      html  css  js  c++  java
  • .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

      

  • 相关阅读:
    怎么让Windows10取消开机登录密码自动登录
    window查看无线网卡bssid以及相关信息命令
    kali-cdlinux-wifi-pj-nanke-心得
    html里文本保留换行格式
    window实用快捷键-ctrl篇
    mybatis 结果映射 collection oftype为string,integer等类型
    Redis集群下只有db0,不支持多db
    软件开发过程中所使用的生命周期模型比较
    简单Dos命令
    简单理解Mysql json数据类型
  • 原文地址:https://www.cnblogs.com/shenghuotaiai/p/13613536.html
Copyright © 2011-2022 走看看