I have an async function signIn
in a Dart program that takes username
and password
string arguments. The function calls a remote server and the server responds with a session token or validation messages in the case of missing or incorrect username and/or password.
Currently I have this implemented with callbacks. The appropriate callback is called after the server responds. No need for await
.
signIn(username, password, onSuccess, onFailure);
The more I read about Dart, I feel like the above isn't really the Dart way of doing things. Should I be using await
combined with try
and catch
? Something like the following?
try {
sessionToken = await signIn(username, password);
// navigate from the sign in screen to the home screen.
} on InvalidParams catch (e) {
// e contains the server's validation messages
// show them to the user.
}
Invalid sign in credentials are likely. Handling them is normal program flow. I was taught never to use try/catch for regular, expected program flow. It seems that the Dart language is encouraging using exception handling for this especially in combination with await
.
From Error class documentation [Emphasis mine.]
If the conditions are not detectable before calling a function, the called function should not throw an Error. It may still throw a value, but the caller will have to catch the thrown value, effectively making it an alternative result rather than an error. The thrown object can choose to implement Exception to document that it represents an exceptional, but not erroneous, occurrence, but it has no other effect than documentation.
What's the best most Dart way to implement this?