How to catch exception in flutter?
Let's say this is your function which throws an exception:
Future<void> foo() async {
throw Exception('FooException');
}
You can either use try-catch
block or catchError
on the Future
since both do the same thing.
Using
try-catch
try { await foo(); } on Exception catch (e) { print(e); // Only catches an exception of type `Exception`. } catch (e) { print(e); // Catches all types of `Exception` and `Error`. }
Use
catchError
await foo().catchError(print);
Try
void loginUser(String email, String password) async {
try {
var user = await _data
.userLogin(email, password);
_view.onLoginComplete(user);
});
} on FetchDataException catch(e) {
print('error caught: $e');
_view.onLoginError();
}
}
catchError
is sometimes a bit tricky to get right.
With async
/await
you can use try
/catch
like with sync code and it is usually much easier to get right.
I was trying to find this answer when got to this page, hope it helps: https://stackoverflow.com/a/57736915/12647239
Basicly i was just trying to catch an error message from a method, but i was calling
throw Exception("message")
And in "catchError" i was getting "Exception: message" instead of "message".
catchError(
(error) => print(error)
);
fixed with the return in the above reference