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

时间:2019-01-25 09:04:58

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

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

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

我到底想做些什么吗?

更新

  

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

     

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

     

具有:

     

return Task.CompletedTask;

1 个答案:

答案 0 :(得分:2)

您可以考虑在mongoose.Promise = global.Promise; // Use this line. mongoose.connect('mongodb://url', { useMongoClient: true }, function (err) { if (err) { console.log('not connected to data base'); } else { console.log('Successfully Connected to database'); } });

下添加日志记录,而不是调用两种不同的异常处理中间件
Home/Error

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

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

并只需在IApplicationBuilder方法中注册它

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