【问题标题】:Exceptions handled in UseExceptionHandler are logged by Application Insights, but they shouldnt在 UseExceptionHandler 中处理的异常由 Application Insights 记录,但它们不应该
【发布时间】:2019-07-18 07:57:01
【问题描述】:

我在program.cs中初始化登录:

 public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseApplicationInsights()
            .UseStartup<Startup>();

后来我在 Startup.cs 中有一些全局异常处理:

public static void ConfigureExceptionHandler(this IApplicationBuilder app)
    {
        app.UseExceptionHandler(appError =>
        {
            appError.Run(async context =>
            {
                context.Response.StatusCode = 200;
            });
        });
    }

我注意到,我的 ITelemetryProcessor 中的代码在 app.UseExceptionHandler 中的代码之前执行。

因此,处理的异常被记录到 Application Insights。如何预防?

【问题讨论】:

    标签: asp.net-core azure-application-insights


    【解决方案1】:

    好的,所以我找到了一个不错的解决方法。我使用自定义中间件来更改响应代码,因此只要在中间件中处理异常就不会弹出见解。示例:

    public class ExceptionHandlingMiddleware
    {
        private readonly RequestDelegate _next;
    
        public ExceptionHandlingMiddleware(RequestDelegate next)
        {
            _next = next;
        }
    
        public async Task InvokeAsync(HttpContext httpContext)
        {
            try
            {
                await _next(httpContext);
            }
            catch (Exception ex)
            {
                httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-14
      • 1970-01-01
      • 2010-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多