CodeGo.net>如何配置多个异常处理程序
我试图将我的中间件管道配置为使用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错误:

enter image description here

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

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

更新:

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;

最佳答案
您可以考虑在主目录/错误目录下添加日志记录,而不是调用两种不同的异常处理中间件

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

或者,您可以使用自定义Expception Handling中间件

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>();
  }
点击查看更多相关文章

转载注明原文:CodeGo.net>如何配置多个异常处理程序 - 乐贴网