Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import 'dart:async';
- /// Example app showing how exceptions are not caught if they have not been awaited
- /// by the time they complete.
- ///
- /// Outputs: """
- /// caught Exception: Top level error
- /// Uncaught Error: Exception: rpc error
- /// """
- Future<void> main() async {
- try {
- final transaction = SimplifiedTransaction();
- final futures = <Future<int>>[];
- futures.add(transaction.createRpc().send().first);
- // The exception from this RPC leaks because the future has not been awaited
- // by the time it completes.
- futures.add(transaction.createRpc(error: 'rpc error').send().first);
- await transaction.commit();
- final results = await Future.wait(futures);
- print('got results: $results');
- } on Exception catch(e) {
- print('caught $e');
- }
- }
- class SimplifiedTransaction {
- final _rpcs = <FakeRpc>[];
- FakeRpc createRpc({String error}) {
- _rpcs.add(FakeRpc()..error = error);
- return _rpcs.last;
- }
- Future<void> commit() {
- for (final rpc in _rpcs) rpc.complete();
- if (_rpcs.any((rpc) => rpc.error != null)) {
- return Future.error(Exception('Top level error'));
- }
- return Future.value();
- }
- }
- class FakeRpc {
- String error;
- final _sc = StreamController<int>.broadcast();
- Stream<int> send() => _sc.stream;
- void complete() {
- Future.delayed(Duration(milliseconds: 50)).then((_) {
- if (error != null) _sc.addError(Exception(error));
- else _sc.add(200);
- _sc.close();
- });
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement