【问题标题】:How to configure multiple exception handlers如何配置多个异常处理程序
【发布时间】:2019-06-19 02:14:45
【问题描述】:

我正在尝试将我的中间件管道配置为使用 2 个不同的异常处理程序来处理相同的异常。例如,我试图让我的自定义处理程序和内置 DeveloperExceptionPageMiddleware 如下:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();                
        app.ConfigureCustomExceptionHandler();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");                               
        app.ConfigureCustomExceptionHandler();            
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseCookiePolicy();
    app.UseAuthentication();
    app.UseMvcWithDefaultRoute();
}

我的目标是让自定义处理程序做自己的事情(日志记录、遥测等),然后将 (next()) 传递给显示页面的其他内置处理程序。我的自定义处理程序如下所示:

public static class ExceptionMiddlewareExtensions
{
    public static void ConfigureCustomExceptionHandler(this IApplicationBuilder app)
    {            
        app.UseExceptionHandler(appError =>
        {
            appError.Use(async (context, next) =>
            {                    
                var contextFeature = context.Features.Get<IExceptionHandlerFeature>();
                if (contextFeature != null)
                {
                    //log error / do custom stuff

                    await next();
                }
            });
        });
    }
}

我无法让 CustomExceptionHandler 将处理传递给下一个中间件。我得到的是以下页面:

404 错误:

我尝试切换顺序,但随后开发人员异常页面接管并且未调用自定义异常处理程序。

我正在尝试做的事情可能吗?

更新:

解决方案是采用 Simonare 的原始建议,并在 Invoke 方法中重新抛出异常。我还必须通过在HandleExceptionAsync 方法中替换以下内容来消除任何类型的响应干预:

context.Response.ContentType = "application/json"; context.Response.StatusCode = (int)code; return context.Response.WriteAsync(result);

与:

return Task.CompletedTask;

【问题讨论】:

    标签: c# asp.net-core asp.net-core-middleware


    【解决方案1】:

    这里有一个非常简单的版本,如何使用自定义异常处理逻辑同时内置 ASP.NET Core 错误页面:

    app.UseExceptionHandler("/Error"); //use standard error page
    app.Use(async (context, next) => //simple one-line middleware
    {
        try
        {
            await next.Invoke(); //attempt to run further application code
        }
        catch (Exception ex) //something went wrong
        {
            //log exception, notify the webmaster, etc.
            Log_Exception_And_Send_Email_or_Whatever(ex);
            //re-throw the exception so it's caught by the outer "UseExceptionHandler"
            throw;
        }
    });
    

    附:嗯,我在答案中添加了明确的 language: c# 提示,但语法突出显示仍然没有将 catch 视为关键字...有趣。

    【讨论】:

      【解决方案2】:

      您可以考虑在Home/Error 下添加日志记录,而不是调用两个不同的异常处理中间件

      [AllowAnonymous]
      public IActionResult Error()
      {
          //log your error here
          return View(new ErrorViewModel 
              { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
      }
      

      或者,您可以使用自定义异常处理中间件

      public class ErrorHandlingMiddleware
      {
          private readonly RequestDelegate _next;
      
          public ErrorHandlingMiddleware(RequestDelegate next)
          {
              _next = next;
          }
      
          public async Task Invoke(HttpContext context, IHostingEnvironment env)
          {
              try
              {
                  await _next(context);
              }
              catch (Exception ex)
              {
                  if (!context.Response.HasStarted)
                      await HandleExceptionAsync(context, ex, env);
                  throw;
              }
          }
      
          private Task HandleExceptionAsync(HttpContext context, Exception exception, IHostingEnvironment env)
          {
              var code = HttpStatusCode.InternalServerError; // 500 if unexpected
              var message = exception.Message;
      
              switch (exception)
              {
                  case NotImplementedException _:
                      code = HttpStatusCode.NotImplemented; 
                      break;
                  //other custom exception types can be used here
                  case CustomApplicationException cae: //example
                      code = HttpStatusCode.BadRequest;
                      break;
              }
      
              Log.Write(code == HttpStatusCode.InternalServerError ? LogEventLevel.Error : LogEventLevel.Warning, exception, "Exception Occured. HttpStatusCode={0}", code);
      
      
              context.Response.ContentType = "application/json";
              context.Response.StatusCode = (int)code;
              return Task.Completed;
          }
      }
      

      只需在 IApplicationBuilder 方法中注册它

        public void Configure(IApplicationBuilder app)
        {
              app.UseMiddleware<ErrorHandlingMiddleware>();
        }
      

      【讨论】:

      • 感谢您的回复。您的建议是始终使用一个异常处理程序,但我想保留默认的开发人员异常页面,同时通过利用中间件管道进行我自己的自定义日志记录。
      • ErrorHandlingMiddleware 将为您工作。您可以拥有尽可能多的中间件处理程序(当然要记住它们对性能有影响)
      • 您能否更新您的答案以包括如何将ErrorHandlingMiddleware 与内置的app.UseDeveloperExceptionPage()app.UseExceptionHandler("/Home/Error") 中间件并排注册?我已经尝试实现该类,但它仍然完全接管了其他内置中间件。
      • 嗨西蒙娜,谢谢!一旦我了解了中间件类是如何工作的,我就设法让它通过一个小的调整来工作。要将异常传递给管道中的下一个中间件,只需在 Invoke 方法中重新抛出异常即可。
      • Simonare,请通过添加“throw;”来更新您的答案在 Invoke 的 catch 块的末尾,还返回 Task.Completed 而不是 context.Response.WriteAsync(result);
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-14
      相关资源
      最近更新 更多