我想避免记录不同类型的取消请求,我不确定这里的最佳做法是什么。我在 GitHub post 中发现开发人员正在以这种方式检查不同类型:
private static bool IsCancellationException(Exception ex)
{
if (ex == null) return false;
if (ex is OperationCanceledException)
return true;
if (ex is System.IO.IOException && ex.Message == "The client reset the request stream.")
return true;
if (ex is Microsoft.AspNetCore.Connections.ConnectionResetException)
return true;
// .NET SQL has a number of different exceptions thrown when operations are cancelled
if (ex.Source == "Microsoft.Data.SqlClient" && ex.Message == "Operation cancelled by user.")
return true;
if ((ex is Microsoft.Data.SqlClient.SqlException || ex is System.Data.SqlClient.SqlException) &&
ex.Message.Contains("Operation cancelled by user"))
return true;
return false;
}
但它对我来说真的很难看,所以我想到了这个:
// ExceptionHandlingMiddleware
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex) when (context.RequestAborted.IsCancellationRequested)
{
HandleCancellationException(context, ex);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
检查
context.RequestAborted.IsCancellationRequested
是否足以忽略已取消的任务?
从我读到的文档中,
IsCancellationRequested
只保证请求取消,所以我想任务可能没有真正取消和失败,但我真的会在意吗,因为客户也没有?
这显然不能处理服务器取消任务的情况,但我实际上想在日志中看到这些,而不是客户端发起的取消。
我也可以处理
OperationCanceledException
但我认为这已经被第一个 catch 涵盖了,所以我可能不需要它而且无论如何我只对忽略客户取消感兴趣。
这里的最佳实践是什么?谢谢!