gpt4 book ai didi

android - Flutter-dart http 库 ClientException

转载 作者:IT王子 更新时间:2023-10-29 07:06:06 25 4
gpt4 key购买 nike

我正在使用 HTTP dart 包 在 flutter 中执行这样的发布请求,但有时当网络出现故障时,IOClient 会抛出 ClientException类,但我在 catch block 和应用程序崩溃中没有得到任何东西。

http.post(url, headers: headers, body: body).then((response) {
//response parsing
}).catchError((error) {
//ClientException is never catched in this block.
});

最佳答案

package:http/src/io_client.dart中所述:

Any internal HTTP errors should be wrapped as [ClientException]s.

docs 中所述这是一个明显的例子:

Potential problem: accidentally mixing synchronous and asynchronous errors

要解决此问题,您需要将代码包装在 Future.sync() 中。

Future.sync() makes your code resilient against uncaught exceptions. If your function has a lot of code packed into it, chances are that you could be doing something dangerous without realizing it:

return new Future.sync(() {
http.post(url, headers: headers, body: body).then((response) {});
});

Future.sync() not only allows you to handle errors you know might occur, but also prevents errors from accidentally leaking out of your function.

关于android - Flutter-dart http 库 ClientException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52515258/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com