为什么我无法捕获异常?

时间:2020-03-31 09:46:21

标签: asynchronous flutter dart async-await

try {
  final result = await http.get(pingUrl)
    .catchError((e) => print(e));
  return result;
} catch (e) {
  print(e)
}

但是我得到了: enter image description here

为什么我不能在catch块中处理异常?

1 个答案:

答案 0 :(得分:1)

不,因为您正在追赶未来。

您将来不应该导管:

try {
  final result = await http.get(pingUrl);
    // .catchError((e) => print(e)); <- removed
  return result;
} catch (e) {
  print(e)
}

或再次抛出catchError:

try {
  final result = await http.get(pingUrl)
    .catchError((e) {
       print(e);
       throw foo;
    });

  return result;
} catch (e) {
  print(e)
}

我更喜欢第一种选择。