首页 > 解决方案 > 如何在颤动中捕获异常?

问题描述

这是我的例外课程。异常类已经由flutter的抽象异常类实现。我错过了什么吗?

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);
}

当状态不是 200 时,CatchError 不会捕获错误。简而言之,捕获的错误不会打印。

标签: flutterdartexceptionmodel-view-controllerflutter-layout

解决方案


尝试

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有时很难做到正确。使用async/await你可以使用try/ catchlike 同步代码,而且通常更容易正确。


推荐阅读