How to catch exception in flutter?
Solution 1
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.
Solution 2
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);
Solution 3
To handle errors in an async
and await
function, use try-catch
:
Run the following example to see how to handle an error from an asynchronous function.
Future<void> printOrderMessage() async {
try {
var order = await fetchUserOrder();
print('Awaiting user order...');
print(order);
} catch (err) {
print('Caught error: $err');
}
}
Future<String> fetchUserOrder() {
// Imagine that this function is more complex.
var str = Future.delayed(
Duration(seconds: 4),
() => throw 'Cannot locate user order');
return str;
}
Future<void> main() async {
await printOrderMessage();
}
Within an async function, you can write try-catch clauses
the same way you would in synchronous code.
Solution 4
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
P-RAD
New into developement never done something big ....:( <3 Loves coding and keep doing it.. <3
Updated on October 30, 2021Comments
-
P-RAD over 2 years
This is my exception class. Exception class has been implemented by the abstract exception class of flutter. Am I missing something?
class FetchDataException implements Exception { final _message; FetchDataException([this._message]); String toString() { if (_message == null) return "Exception"; return "Exception: $_message"; } } void loginUser(String email, String password) { _data .userLogin(email, password) .then((user) => _view.onLoginComplete(user)) .catchError((onError) => { print('error caught'); _view.onLoginError(); }); } Future < User > userLogin(email, password) async { Map body = { 'username': email, 'password': password }; http.Response response = await http.post(apiUrl, body: body); final responseBody = json.decode(response.body); final statusCode = response.statusCode; if (statusCode != HTTP_200_OK || responseBody == null) { throw new FetchDataException( "An error occured : [Status Code : $statusCode]"); } return new User.fromMap(responseBody); }
CatchError doesn't catch the error when the status is not 200. In short error caught is not printed.
-
CopsOnRoad over 5 yearsGünter, I think we can't use
await
after method parameters ends. You should useasync
there. I am not having IDE right now, so can't check ifawait
is valid there. -
Günter Zöchbauer over 5 yearsThanks, should have been
async