我正在实现一个返回 Stream 的函数。我不确定如何实现错误处理,最佳实践是什么?
对于返回 Future 的函数,最好不要抛出同步错误。对于返回 Stream 的函数也是如此吗?
这是我在想的一个例子:
Stream<int> count() {
var controller = new StreamController<int>();
int i = 0;
try {
doSomethingThatMightThrow();
new Timer.repeating(new Duration(seconds: 1), () => controller.add(i++));
} on Exception catch (e) {
controller.addError(e);
controller.close();
}
return controller.stream;
}