Search code examples
flutterdartexceptionmodel-view-controllerflutter-layout

How to catch exception in flutter?


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.


Solution

  • 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.