如何配置多个异常处理程序

How to configure multiple exception handlers

我正在尝试将我的中间件管道配置为使用 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();
}

我的 objective 是让自定义处理程序执行自己的操作(日志记录、遥测等),然后将 (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 错误:

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

我正在尝试做的事情是否可行?

更新:

The solution was to take Simonare's original suggestion and re-throw the exception in the Invoke method. I also had to remove any type of response-meddling by replacing the following in HandleExceptionAsync method:

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

with:

return Task.CompletedTask;

您可以考虑在 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>();
  }

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

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;
    }
});

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