Skip to content

Instantly share code, notes, and snippets.

@jonahwilliams
Created March 16, 2022 22:41
Show Gist options
  • Save jonahwilliams/eebd0a2bba7d88d0e9969a68b4bc4a59 to your computer and use it in GitHub Desktop.
Save jonahwilliams/eebd0a2bba7d88d0e9969a68b4bc4a59 to your computer and use it in GitHub Desktop.
uncaught gist
import 'dart:async';
void main() async {
String? callbacker(void Function(Object? arg) cb) {
cb(null); // indicates failure
}
Object? error;
try {
await _futurize(callbacker);
} catch (err) {
error = err;
}
print(error);
}
typedef _Callback<T> = void Function(T result);
typedef _Callbacker<T> = String? Function(_Callback<T?> callback);
// This is an exact copy of the function defined in painting.dart. If you change either
// then you must change both.
Future<T> _futurize<T>(_Callbacker<T> callbacker) {
final Completer<T> completer = Completer<T>.sync();
// If the callback synchronously throws an error, then synchronously
// rethrow that error instead of adding it to the completer. This
// prevents the Zone from receiving an uncaught exception.
bool sync = true;
final String? error = callbacker((T? t) {
if (t == null) {
// remove the `if (sync)` condition for a demonstration
if (sync) {
throw Exception('operation failed');
} else {
completer.completeError(Exception('operation failed'));
}
} else {
completer.complete(t);
}
});
sync = false;
if (error != null)
throw Exception(error);
return completer.future;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment