Created
February 24, 2025 12:43
-
-
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.
This file contains 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
(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); | |
} | |
} |
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
Below is the test file.