I would like to have an exception thrown inside stream to be caught and handled outside by the caller.
If I try with a standard try-catch block, like below, it does work: I get Uncaught Error: Exception.
By running the snippet code below in DartPad
void main() async {
await for (var i in mainStream()) {
print(i);
}
}
Stream<int> subStreamA() async* {
for (var i in List.generate(10, (i) => i)) {
if (i == 2) {
throw Exception();
}
yield i;
}
}
Stream<int> subStreamB() async* {
for (var i in List.generate(10, (i) => i + 10)) {
yield i;
}
}
Stream<int> mainStream() async* {
try {
yield* subStreamA();
yield* subStreamB();
} catch (e) {
print('CAUGHT! :)');
yield -1;
}
}
The result is:
0
1
Uncaught Error: Exception
I would like the exception to be caught, resulting in:
0
1
CAUGHT! :)
-1
I had some "solution" in mind, but they're kind of horrible :( such as...
Stream<int> mainStream() async* {
try {
Exception? err;
yield* subStreamA().handleError((e) {
err = e;
});
if (err != null) throw err!;
yield* subStreamB().handleError((e) {
err = e;
});
if (err != null) throw err!;
} catch (e) {
print('CAUGHT! :)');
yield -1;
}
}
Is there a clean solution leveraging a normal try-catch without dirty tricks?