Почему исключение не перехватывается таким образом в асинхронной функции в Dart?

#dart #async-await

#dart #async-await

Вопрос:

 Future<void> fetchUserOrder() async {
// Imagine that this function is fetching user info but encounters a bug
  try {
  return Future.delayed(const Duration(seconds: 2),
      () => throw Exception('Logout failed: user ID is invalid'));
    
  } catch(e) {
    // Why exception is not caught here?
    print(e);
  }
}

void main() {
  fetchUserOrder();
  print('Fetching user order...');
}
 

Он выводит

 Fetching user order...
Uncaught Error: Exception: Logout failed: user ID is invalid
 

В котором говорится, что исключение не перехвачено. Но, как вы видите, throw Exception предложение окружено try catch .

Комментарии:

1. Вы можете попробовать код здесь: dart.dev/codelabs/async-await

Ответ №1:

Блок try-catch будет перехватывать только исключение ожидаемого будущего. Поэтому вы должны использовать await в своем коде:

 Future<void> fetchUserOrder() async {
// Imagine that this function is fetching user info but encounters a bug
  try {
  return await Future.delayed(const Duration(seconds: 2),
      () => throw Exception('Logout failed: user ID is invalid'));
    
  } catch(e) {
    // Why exception is not caught here?
    print(e);
  }
}

void main() {
  fetchUserOrder();
  print('Fetching user order...');
}