如果我嵌套了 async* 流,则似乎无法捕获异常,这是违反直觉的。
一个例子:
void main() {
getString().listen(print);
}
Stream<String> getString() async* {
try {
yield* asyncStarError();
yield await asyncError();
} catch (err) {
yield 'Crash';
}
}
Stream<String> asyncStarError() async* {
throw Exception('A Stream error happened');
}
Future<String> asyncError() async {
throw Exception('A Future error happened');
}
这输出:
Uncaught Error: Exception: A Stream error happened
Crash
所以抛出的异常asyncStarError
没有被捕获,而Future按预期被捕获。谁能解释为什么?
您可以在 dartpad 中观察行为:https ://dartpad.dartlang.org