Advertisement
Guest User

Untitled

a guest
Jun 18th, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.46 KB | None | 0 0
  1. import 'dart:async';
  2.  
  3. /// Example app showing how exceptions are not caught if they have not been awaited
  4. /// by the time they complete.
  5. ///
  6. /// Outputs: """
  7. /// caught Exception: Top level error
  8. /// Uncaught Error: Exception: rpc error
  9. /// """
  10. Future<void> main() async {
  11. try {
  12. final transaction = SimplifiedTransaction();
  13. final futures = <Future<int>>[];
  14. futures.add(transaction.createRpc().send().first);
  15.  
  16. // The exception from this RPC leaks because the future has not been awaited
  17. // by the time it completes.
  18. futures.add(transaction.createRpc(error: 'rpc error').send().first);
  19.  
  20. await transaction.commit();
  21. final results = await Future.wait(futures);
  22. print('got results: $results');
  23. } on Exception catch(e) {
  24. print('caught $e');
  25. }
  26. }
  27.  
  28. class SimplifiedTransaction {
  29. final _rpcs = <FakeRpc>[];
  30.  
  31. FakeRpc createRpc({String error}) {
  32. _rpcs.add(FakeRpc()..error = error);
  33. return _rpcs.last;
  34. }
  35.  
  36. Future<void> commit() {
  37. for (final rpc in _rpcs) rpc.complete();
  38. if (_rpcs.any((rpc) => rpc.error != null)) {
  39. return Future.error(Exception('Top level error'));
  40. }
  41. return Future.value();
  42. }
  43. }
  44.  
  45. class FakeRpc {
  46. String error;
  47. final _sc = StreamController<int>.broadcast();
  48.  
  49. Stream<int> send() => _sc.stream;
  50.  
  51. void complete() {
  52. Future.delayed(Duration(milliseconds: 50)).then((_) {
  53. if (error != null) _sc.addError(Exception(error));
  54. else _sc.add(200);
  55. _sc.close();
  56. });
  57. }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement