async_guard.dart 5.03 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6 7 8 9 10 11 12 13
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

/// Runs [fn] with special handling of asynchronous errors.
///
/// If the execution of [fn] does not throw a synchronous exception, and if the
/// [Future] returned by [fn] is completed with a value, then the [Future]
/// returned by [asyncGuard] is completed with that value if it has not already
/// been completed with an error.
///
14 15 16 17 18 19
/// If the execution of [fn] throws a synchronous exception, and no [onError]
/// callback is provided, then the [Future] returned by [asyncGuard] is
/// completed with an error whose object and stack trace are given by the
/// synchronous exception. If an [onError] callback is provided, then the
/// [Future] returned by [asyncGuard] is completed with its result when passed
/// the error object and stack trace.
20 21
///
/// If the execution of [fn] results in an asynchronous exception that would
22 23 24 25 26
/// otherwise be unhandled, and no [onError] callback is provided, then the
/// [Future] returned by [asyncGuard] is completed with an error whose object
/// and stack trace are given by the asynchronous exception. If an [onError]
/// callback is provided, then the [Future] returned by [asyncGuard] is
/// completed with its result when passed the error object and stack trace.
27 28
///
/// After the returned [Future] is completed, whether it be with a value or an
29
/// error, all further errors resulting from the execution of [fn] are ignored.
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
///
/// Rationale:
///
/// Consider the following snippet:
/// ```
/// try {
///   await foo();
///   ...
/// } catch (e) {
///   ...
/// }
/// ```
/// If the [Future] returned by `foo` is completed with an error, that error is
/// handled by the catch block. However, if `foo` spawns an asynchronous
/// operation whose errors are unhandled, those errors will not be caught by
/// the catch block, and will instead propagate to the containing [Zone]. This
/// behavior is non-intuitive to programmers expecting the `catch` to catch all
/// the errors resulting from the code under the `try`.
///
/// As such, it would be convenient if the `try {} catch {}` here could handle
/// not only errors completing the awaited [Future]s it contains, but also
51
/// any otherwise unhandled asynchronous errors occurring as a result of awaited
52 53 54
/// expressions. This is how `await` is often assumed to work, which leads to
/// unexpected unhandled exceptions.
///
55
/// [asyncGuard] is intended to wrap awaited expressions occurring in a `try`
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
/// block. The behavior described above gives the behavior that users
/// intuitively expect from `await`. Consider the snippet:
/// ```
/// try {
///   await asyncGuard(() async {
///     var c = Completer();
///     c.completeError('Error');
///   });
/// } catch (e) {
///   // e is 'Error';
/// }
/// ```
/// Without the [asyncGuard] the error 'Error' would be propagated to the
/// error handler of the containing [Zone]. With the [asyncGuard], the error
/// 'Error' is instead caught by the `catch`.
71 72 73 74 75 76 77 78 79 80
///
/// [asyncGuard] also accepts an [onError] callback for situations in which
/// completing the returned [Future] with an error is not appropriate.
/// For example, it is not always possible to immediately await the returned
/// [Future]. In these cases, an [onError] callback is needed to prevent an
/// error from propagating to the containing [Zone].
///
/// [onError] must have type `FutureOr<T> Function(Object error)` or
/// `FutureOr<T> Function(Object error, StackTrace stackTrace)` otherwise an
/// [ArgumentError] will be thrown synchronously.
81 82
Future<T> asyncGuard<T>(
  Future<T> Function() fn, {
83
  Function? onError,
84
}) {
85 86 87 88 89 90 91
  if (onError != null &&
      onError is! _UnaryOnError<T> &&
      onError is! _BinaryOnError<T>) {
    throw ArgumentError('onError must be a unary function accepting an Object, '
                        'or a binary function accepting an Object and '
                        'StackTrace. onError must return a T');
  }
92 93
  final Completer<T> completer = Completer<T>();

94 95 96 97 98 99 100 101
  void handleError(Object e, StackTrace s) {
    if (completer.isCompleted) {
      return;
    }
    if (onError == null) {
      completer.completeError(e, s);
      return;
    }
102
    if (onError is _BinaryOnError<T>) {
103
      completer.complete(onError(e, s));
104
    } else if (onError is _UnaryOnError<T>) {
105
      completer.complete(onError(e));
106 107 108
    }
  }

109 110 111 112 113 114
  runZoned<void>(() async {
    try {
      final T result = await fn();
      if (!completer.isCompleted) {
        completer.complete(result);
      }
115 116
    // This catches all exceptions so that they can be propagated to the
    // caller-supplied error handling or the completer.
117
    } catch (e, s) { // ignore: avoid_catches_without_on_clauses, forwards to Future
118
      handleError(e, s);
119
    }
120
  }, onError: (Object e, StackTrace s) { // ignore: deprecated_member_use
121
    handleError(e, s);
122 123 124 125
  });

  return completer.future;
}
126 127 128

typedef _UnaryOnError<T> = FutureOr<T> Function(Object error);
typedef _BinaryOnError<T> = FutureOr<T> Function(Object error, StackTrace stackTrace);