我有这样的东西:
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();
}
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();
}
如果您不需要对错误进行任何处理并希望忽略所有失败,您也可以在ignore
s
上使用
Future
扩展方法:
void main() async {
f1();
f2().ignore();
await f3();
}