Created
March 16, 2022 22:41
-
-
Save jonahwilliams/eebd0a2bba7d88d0e9969a68b4bc4a59 to your computer and use it in GitHub Desktop.
uncaught gist
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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