.NET 7 避免在数据库查询中记录由取消标记抛出的异常

问题描述 投票:0回答:0

我正在开发 ASP.NET 7.0 应用程序。这个应用程序向数据库发出请求,并传递给它一个取消令牌。

public async Task OnGetAsync(CancellationToken cancellationToken)
{
    PageDisabled = await _db.MyTable
        .AnyAsync(cancellationToken: cancellationToken);
}

使用此代码,在抛出取消令牌时会记录以下异常(显示的文本被截断):

fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[1]
      An unhandled exception has occurred while executing the request.
      System.Threading.Tasks.TaskCanceledException: A task was canceled.
         at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
...

这污染了我的日志,我想避免它被记录。由于我有多个这样的查询,我想避免每次都使用 try catch 块以使代码更清晰。

有没有办法在不使用 try/catch 块的情况下过滤掉这个特定的日志消息?

我尝试将其添加到 LogLevel 部分的 appsettings.json 文件中:

"System.Threading.Tasks.TaskCanceledException": "None"
但它没有用(我认为你必须将 ExceptionHandlerMiddleware 的日志级别设置为 None,但它不再特定于任务取消异常)。

我还尝试添加自定义异常处理程序:

app.UseExceptionHandler(errorApp =>
{
    errorApp.Run(async context =>
    {
        var exception = context.Features.Get<IExceptionHandlerFeature>()?.Error;

        if (exception?.Message == "A task was canceled.")
        {
            await context.Response.WriteAsync("Task cancelled.");
            // How do I ignore this error afterwards?

        }
        else
        {
            // redirect to the error page
            context.Response.Redirect("/Error");
        }
    });
});

通过中间件后仍然会记录错误。也许有办法修改上下文变量来避免它?

context.Features.Get<IExceptionHandlerFeature>().Error
是只读的,所以我不能将它设置为空。

asp.net logging cancellation-token exceptionhandler
© www.soinside.com 2019 - 2024. All rights reserved.