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.
Handling Exceptions in Flutter The try block contains the code that might possibly throw an exception. The try block must be followed by on or catch blocks, and an optional finally block. The catch block is used to catch and handle any exceptions thrown in the try block.
As stated in the error, "to fix this problem, create a new project by running flutter create -t app and then move the dart code, assets and pubspec. yaml to the new project." What you need to do is run the command line command `flutter create -t app ' (where is the location of the new project.
That error is handled by catchError() . If myFunc() 's Future completes with an error, then() 's Future completes with that error. The error is also handled by catchError() . Regardless of whether the error originated within myFunc() or within then() , catchError() successfully handles it.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With