当我不等待 Future 时,如何处理从 Futures 返回的错误?

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

我有这样的东西:

Future<void> f1() { ... }
Future<void> f2() { ... }
Future<void> f3() { ... }

void main() async
{
  f1();
  f2(); // might throw an Exception

  await f3();
}

注意 - 我故意不等待 f1 或 f2,我只是等待 f3 的结果。

如何处理 f2 中出现异常的可能性?正常的 try / catch 过程不起作用。

我看过一些关于catchError的讨论,但我不太明白。

我想做相当于:

Future<void> f1() { ... }
Future<void> f2() { ... }
Future<void> f3() { ... }

void main() async
{
  f1();
  try 
  {
    f2(); // might throw an Exception
  }
  on MyException catch( e )
  {
    print('this is what I expected to happen, so carry on regardless');
  }

  await f3();
}
dart exception future
1个回答
0
投票

正如您所指出的,您可以使用

Future.catchError

void main() async {
  f1();
  f2().catchError(
    (e) => print('this is what I expected to happen, so carry on regardless'),
    test: (e) => e is MyException,
  );

  await f3();
}

请注意,

Future.catchError
使用起来可能很棘手。您始终可以将 Future
 包装在另一个使用 
await
try
-
catch
:
的函数中

void main() async { f1(); void ignoreFailure(Future<void> future) async { try { await future; } on MyException catch (e) { print('this is what I expected to happen, so carry on regardless'); } } ignoreFailure(f2()); await f3(); }
如果您不需要对错误进行任何处理并希望忽略

所有失败,您也可以在ignores

上使用
Future
扩展方法:

void main() async { f1(); f2().ignore(); await f3(); }
    
© www.soinside.com 2019 - 2024. All rights reserved.