为什么在调用异步函数后未捕获到错误

时间:2019-11-11 22:29:25

标签: flutter dart

为什么我的第二个try-catch块中没有捕获我的错误,请考虑以下代码

在我的提供程序类中:

void addProduct(Product product) async {
    try {
      const url = '...';
      final response = await http.post(url,
          body: json.encode({
            'title': product.title,
            'description': product.description,
            'price': product.price,
            'imageUrl': product.imageUrl,
          }));

      final String id = json.decode(response.body)['name'];
      final productToAdd = Product(
        id: id,
        description: product.description,
        imageUrl: product.imageUrl,
        price: product.price,
        title: product.title,
      );
      _products.add(productToAdd);
      notifyListeners();
    } catch (onError) {
      print(onError); // it did log the error here
      throw onError; // stack was printed at this point instead of re-throw
    }
  }

在我的小部件中:

 try {
        Provider.of<Products>(context, listen: false)
            .addProduct(_editedProduct);
      } catch (error) {
        print('entered error'); //never reached this point
        showDialog( // never shown
            context: context,
            builder: (ctx) {
              return AlertDialog(
                title: Text('An error hapened!'),
                content: Text('Something went wrong while adding the product!'),
                actions: <Widget>[
                  FlatButton(
                    child: Text('ok'),
                    onPressed: () {
                      Navigator.of(ctx).pop();
                    },
                  )
                ],
              );
            });
      }

从Java的背景来看,该错误应该传播到另一个try-catch块中,但是没有传播。

有人可以解释吗?

非常感谢

0 个答案:

没有答案