Exception Future.wait()未捕获异常(Dart)

Exception Future.wait()未捕获异常(Dart),exception,flutter,dart,Exception,Flutter,Dart,在我的Flitter应用程序中,我想同时拨打多个网络电话,然后在所有电话都完成后再做一些事情。为此,我使用了Future.wait(),这正是我想要的。然而,当调用失败时,它抛出一个异常,异常处理程序不知何故没有捕获到该异常(即未捕获异常) 当我单独执行wait\u fetchSomeData()时(在Future.wait()之外),异常处理程序会按预期调用异常 Future<bool> someMethod() async { try { var res

在我的Flitter应用程序中,我想同时拨打多个网络电话,然后在所有电话都完成后再做一些事情。为此,我使用了
Future.wait()
,这正是我想要的。然而,当调用失败时,它抛出一个异常,异常处理程序不知何故没有捕获到该异常(即未捕获异常)

当我单独执行
wait\u fetchSomeData()
时(在
Future.wait()
之外),异常处理程序会按预期调用异常

  Future<bool> someMethod() async {

    try {
      var results = await Future.wait([
        _fetchSomeData(),
        _fetchSomeOtherData()
      ]);
      //do some stuf when both have finished...
      return true;
    }
    on Exception catch(e) {
      //does not get triggered somehow...
      _handleError(e);
      return false;
    }
  } 
因此,如果从
\u someMethod()
中删除wait行,或者在
Future之外调用
\u someMethod()
,wait()
将防止未捕获的异常。这当然是最不幸的,我需要等待http调用。。。飞镖里的虫子


我已启用未捕获异常断点。如果我关掉这个,问题似乎就消失了。也许这是调试器的问题。我使用的是Visual Studio代码和最新的Flitter。

我认为您被未来误导了一点。等等()
Future.wait()

现在既然
Future.wait()
仍然是未来。您可以通过两种方式进行处理:

  • 使用
    等待
    尝试捕获
  • 使用
    onError
    回调
  • 这大概是

    Future.wait([futureOne, futureTwo])
    .then((listOfValues) {
        print("ALL GOOD")
     }, 
     onError: (error) { print("Something is not ok") }
    
    在使用Future.wait()时,我需要做什么来捕获异常

    当我使用与您相同的代码时,我发现在
    Future.wait()
    中使用的每个过程内部的代码必须用
    try/catch
    包装,并且在
    catch
    上必须返回
    Future.error()。另外,
    error
    必须设置为
    true

    try {
      await Future.wait([proc1, ...], eagerError: true);
    } on catch(e) {
      print('error: $e')
    }
    
    /// Proc 1
    Future<void> proc1() async {
      try {
        final result = await func();
      } on SomeException catch(e) {
        return Future.error('proc 1 error: $');
      }
    }
    
    试试看{
    等待未来。等待([proc1,…],错误:true);
    }捕获物(e){
    打印('error:$e')
    }
    ///程序1
    Future proc1()异步{
    试一试{
    最终结果=等待函数();
    }关于某些异常捕获(e){
    返回Future.error('proc1错误:$');
    }
    }
    
    可能您正在使用其中一种方法(_fetchSomeData或_fetchSomeOtherData)处理这些异常,并且没有在这些方法之上重新抛出要处理的异常。这个答案可能会有帮助-
    尝试{var result=wait Future.wait([Future.delayed(持续时间:秒数1),()=>first')、Future.delayed(持续时间:秒数2),()=>second'),Future.delayed(持续时间(秒数:3),()=>throw Exception('bad things incident'),]);print('result:$result');}在异常捕获(e){print('error:[$e]');}
    你在日志上看到了什么?是的,我已经缩小了问题的范围。我正在更新我的帖子。请检查我的开篇帖子中的更新信息。你现在可以重现这个问题吗?我已经尝试过这两种方法了,你可以看到我在我的示例中使用了try-catch。@Janneman我没有看到你在哪里使用了
    onError
    callb我也试过了,但是我在我的例子中使用了try/catch方法。我只是用一些更多的信息更新了我的初始帖子。
    try {
      await Future.wait([proc1, ...], eagerError: true);
    } on catch(e) {
      print('error: $e')
    }
    
    /// Proc 1
    Future<void> proc1() async {
      try {
        final result = await func();
      } on SomeException catch(e) {
        return Future.error('proc 1 error: $');
      }
    }