以下代码按照预期的方式工作( .NET 4.8项目的WPF .NET项目的代码隐藏)。
private async Task DeleteAsync()
{
try
{
await ViewModel.DeleteAsync(GetSelectedItems());
}
catch (Exception ex)
{
var doCatch = ex is ValidationException
|| ex is ExpectedInfoException
|| ex is ExpectedDbException;
if (doCatch)
ExeptionHelper.HandleException(ex, AppConstants.ApplicationName);
else
throw;
}
}下面的模拟实验并不总是捕捉到.NET 6.0项目中的异常,请参阅内联注释。我尝试的最低限度的可复制的复制样本还没有完成,但希望有人已经有了一个有教养的猜测的原因?
private async void DeleteListAsync()
{
var list = ViewModel.GetSelectedItems(
dataGrid.SelectedItems.OfType<ActorModel>().ToList());
try
{
await ViewModel.DeleteListAsync(list);
}
catch (Exception ex) when (
ex is ValidationException
|| ex is ExpectedInfoException
|| ex is ExpectedDbException)
{
/* this part does run as expected when() one of those three
* custom MyNamespace.Exceptions gets thrown in the previous `try` block.
* But unexpectedly *not when thrown inside the nested step-into code of
* ViewModel.DeleteListAsync() */
ApplicationHelper.HandleException(ex, Intl.LocalizedConstants.AppName);
}
catch
{
/* this part does run as expected when a `new InvalidOperationException("Test")`
* or `NotImplementedException()` gets thrown directly in the `try`block.
* Also when thrown inside the nested step-into code of
* ViewModel.DeleteListAsync() */
throw;
}
}解决:很久之后,在有用的评论的帮助下,我实际上在嵌套代码的一个隐蔽而黑暗的角落找到了一个缺失的等待语句,就像@Charlieface说的那样,非常感谢大家!
发布于 2022-01-31 02:13:49
显然,您的代码中缺少一个await,这将导致异常被包装在AggregateException中。
await所做的事情之一,以及设置状态机制,是打开包含在运行Task期间抛出的任何异常的AggregateExceptions。因此,如果您希望捕获和处理特定的异常类型,则应该一直使用await。
https://stackoverflow.com/questions/70907575
复制相似问题