我正在尝试使用ContinueWith()包装异步任务可能抛出的异常。如果我只是从继续操作中抛出,事情似乎可以工作,但我的调试器声称异常是未处理的。是我做错了什么,还是这是Visual Studio的问题?有没有一种更干净的方法来做到这一点,或者有一种方法可以解决我的调试器在最终被处理的异常时停止的问题?
下面的测试通过并打印“按预期捕获包装的异常”,但当我调试它时,throw new CustomException行显示为“未被用户代码处理”。
var task = DoWorkAsync().ContinueWith(t => {
throw new CustomException("Wrapped", t.Exception.InnerException); // Debugger reports this unhandled
}, TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously);
try {
task.Wait();
Assert.Fail("Expected work to fail");
} catch (AggregateException ag) {
if (!(ag.InnerException is CustomException))
throw;
}
Console.WriteLine("Caught wrapped exception as expected");发布于 2012-12-20 06:17:12
启用"Just My Code“时,Visual Studio在某些情况下会在引发异常的行断开,并显示一条错误消息"exception not handled by user code”。此错误是良性的。您可以按F5继续并查看这些示例中演示的异常处理行为。为了防止Visual Studio在出现第一个错误时中断,只需取消选中“Tools”>“Options”>“Debugging”>“General”下的"Just My Code“复选框。
来自http://msdn.microsoft.com/en-us/library/dd997415.aspx
发布于 2012-07-27 05:33:20
你似乎没有用延续来“包装”异常,你似乎在延续中抛出了异常。如果DoWorkAsync可以抛出异常,我会将其“包装”在一个延续中,如下所示:
DoWorkAsync().ContinueWith(t=>{
Console.WriteLine("Error occurred: " + t.Exception);
}, TaskContinuationOptions.OnlyOnFaulted);或者,如果你想在异步方法之外“处理”异常,你可以这样做:
var task = DoWorkAsync();
task.Wait();
if(task.Exception != null)
{
Console.WriteLine("Error occurred: " + task.Exception);
}如果你想转换抛出的异常,你可以这样做:
var task = DoWorkAsync().ContinueWith(t=>{
if(t.Exception.InnerExceptions[0].GetType() == typeof(TimeoutException))
{
throw new BackoffException(t.Exception.InnerExceptions[0]);
}
}, TaskContinuationOptions.OnlyOnFaulted);你可以这样处理这个BackoffException:
if(task.IsFaulted)
{
Console.WriteLine(task.Exception.InnerExceptions[0]);
// TODO: check what type and do something other than WriteLine.
}https://stackoverflow.com/questions/11678267
复制相似问题