Skip to content

Instantly share code, notes, and snippets.

@callmephil
Created March 7, 2025 09:18
Show Gist options
  • Save callmephil/d341d2b63c843613b68b52544c77e690 to your computer and use it in GitHub Desktop.
Save callmephil/d341d2b63c843613b68b52544c77e690 to your computer and use it in GitHub Desktop.
Go like error handling in Dart
typedef AsyncErrorRecord = ({Object error, StackTrace? stackTrace});
abstract class Async<T> {
const Async();
static Future<(AsyncErrorRecord? error, T? result)> guard<T>(
Future<T> Function() future,
) async {
try {
final result = await future();
return (null, result);
} catch (e, s) {
return ((error: e, stackTrace: s), null);
}
}
}
Future<void> main() async {
var (err, result) = await Async.guard(() async {
return Future.delayed(Duration(milliseconds: 150), () => 'Hello, world!');
});
if (err != null) {
print(err.error);
return;
}
print(result);
(err, result) = await Async.guard(() async {
return Future.delayed(Duration(milliseconds: 150), () => throw Exception('Just an exception'));
});
if (err != null) {
print(err.error);
return;
}
print(result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment