【问题标题】:Why I can't catch exception?为什么我无法捕获异常?
【发布时间】:2020-03-31 09:46:21
【问题描述】:
try {
  final result = await http.get(pingUrl)
    .catchError((e) => print(e));
  return result;
} catch (e) {
  print(e)
}

但我得到了这个:

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

【问题讨论】:

    标签: asynchronous flutter dart async-await


    【解决方案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)
    }
    

    我更喜欢第一个选项。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-24
      • 2010-11-16
      • 2012-01-22
      • 2015-06-26
      • 2023-03-05
      相关资源
      最近更新 更多