Skip to content

Instantly share code, notes, and snippets.

@sunderee
Created February 24, 2025 12:43
Show Gist options
  • Save sunderee/bed6392fc7f4f6d3933be55f7485c79c to your computer and use it in GitHub Desktop.
Save sunderee/bed6392fc7f4f6d3933be55f7485c79c to your computer and use it in GitHub Desktop.
Native Dart helpers that use records to return the result or thrown error/exception object.
(T?, Object?) tryCatch<T extends Object>(T Function() function) {
try {
final result = function.call();
return (result, null);
} catch (error) {
return (null, error);
}
}
Future<(T?, Object?)> tryCatchAsync<T extends Object>(
Future<T> Function() function,
) async {
try {
final result = await function.call();
return (result, null);
} catch (error) {
return (null, error);
}
}
@sunderee
Copy link
Author

If there's someone enthusiastic enough (or perhaps that's a note to myself at some point in the future), with this approach, we might loose stack trace. Refer to this comment on Twitter.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment