【问题标题】:ErrorHandling Middleware catch is never caughtErrorHandling Middleware catch 永远不会被捕获
【发布时间】:2020-01-25 23:43:56
【问题描述】:

我有这个 ErrorHandlingMiddleware,看起来像这样:

public class ErrorHandlingMiddleware
{
    private readonly RequestDelegate _next;
    public ErrorHandlingMiddleware(RequestDelegate next)
    {
        this._next = next;
    }

    public async Task Invoke(HttpContext context /* other dependencies */)
    {
        try
        {
            await _next(context);
        }
        catch (Exception ex)
        {
            await HandleExceptionAsync(context, ex);
        }
    }

    private static Task HandleExceptionAsync(HttpContext context, Exception ex)
    {
        var statusCode = (int)HttpStatusCode.InternalServerError;

        if (ex is NotFoundError) statusCode = (int)HttpStatusCode.NotFound;
        //else if (ex is MyUnauthorizedException) code = HttpStatusCode.Unauthorized;
        //else if (ex is MyException) code = HttpStatusCode.BadRequest;

        var error = new AttemptError(statusCode, ex.Message, ex);

        context.Response.ContentType = "application/json";
        context.Response.StatusCode = statusCode;

        return context.Response.WriteAsync(error.ToString());
    }
}

我已将此添加到我的 Startup 类中:

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

    app.UseIdentityServer();
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "r3plica Identity Server v1");
        c.OAuthClientId("swagger");
        c.OAuthAppName("Swagger Api UI");
    });
    app.UseMvc();
}

我希望如果我在我的应用程序中的任何地方抛出异常,它会被捕获并执行以下行:

await HandleExceptionAsync(context, ex);

所以,我设置了一个测试:

throw new Exception();

这是在我的控制器中抛出的。当我运行我的应用程序,然后调用引发该异常的端点时,它确实到达了我的ErrorHandlingMiddlewareInvoke 方法,但是没有捕获到异常,它只是转到await _next(context).. ..

有谁知道我做错了什么?

【问题讨论】:

  • 我不确定错误处理程序的注册是否正确。我注册了我的中间件,比如这个 app.UseMiddleware(typeof(ErrorHandlingMiddleware));。也许您的注册也是正确的。

标签: c# error-handling middleware


【解决方案1】:

如果您在 Startup 中的 app.UseDeveloperExceptionPage(); 之后调用使用中间件,您的中间件将会工作。

Handle errors in ASP.NET Core

在要捕获异常的任何中间件之前调用 UseDeveloperExceptionPage。

【讨论】:

    【解决方案2】:

    我通过创建过滤器解决了这个问题:

    public class HttpResponseExceptionFilter : IActionFilter, IOrderedFilter
    {
        public int Order { get; set; } = int.MaxValue - 10;
    
        public void OnActionExecuting(ActionExecutingContext context) { }
    
        public void OnActionExecuted(ActionExecutedContext context)
        {
            if (context.Exception == null) return;
    
            var attempt = Attempt<string>.Fail(context.Exception);
    
            if (context.Exception is AttemptException exception)
            {
                context.Result = new ObjectResult(attempt)
                {
                    StatusCode = exception.StatusCode,
                };
            }
            else
            {
                context.Result = new ObjectResult(attempt)
                {
                    StatusCode = (int)HttpStatusCode.InternalServerError,
                };
            }
    
            context.ExceptionHandled = true;
        }
    }
    

    并像这样注册它:

    services.AddControllers(options => options.Filters.Add(new HttpResponseExceptionFilter()));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-24
      • 2021-08-10
      • 2014-11-06
      • 1970-01-01
      • 2020-11-18
      • 2012-10-27
      相关资源
      最近更新 更多