如何在颤振中捕获异常?

How to catch exception in flutter?

这是我的例外 class。 Exceptionclass已经通过flutter的抽象exceptionclass实现了。我错过了什么吗?

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 不会捕获错误。简而言之,不会打印捕获的错误。

尝试

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/catch,通常更容易正确。

Future < User > userLogin(email, password) async { try {
  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); }
   catch (e){
    print(e.toString());
}

要处理 asyncawait 函数中的错误,请使用 try-catch:

运行下面的例子来看看如何处理来自异步函数的错误。

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

在异步函数中,您可以像在同步代码中一样编写 try-catch clauses

假设您的函数抛出异常:

Future<void> foo() async {
  throw Exception('FooException');
}

您可以在 Future 上使用 try-catch 块或 catchError,因为两者做同样的事情。

  • 使用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`.
    }
    
  • 使用catchError

    await foo().catchError(print);
    

进入此页面时,我正试图找到这个答案,希望对您有所帮助:

基本上我只是想从方法中捕获错误消息,但我正在调用

throw Exception("message")

在“catchError”中,我得到的是“Exception: message”而不是“message”。

catchError(
  (error) => print(error)
);

已修复上述参考中的return