Created
March 7, 2025 09:18
-
-
Save callmephil/d341d2b63c843613b68b52544c77e690 to your computer and use it in GitHub Desktop.
Go like error handling in Dart
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
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