Flutter中如何处理HTTP连接超时崩溃

问题描述 投票:0回答:1

所以我有一个使用Flutter HTTP库的方法,并负责使用如下代码调用对服务器的HTTP请求:

Future<List<DataModel>> fetchData() async {
  try {
    var url = Uri.parse('${baseUrlParse}myapipath');
    var request = await http.get(url);

    var data = jsonDecode(request.body);

    return data;
  } catch (e) {
    print('Catch ${e}');
    rethrow;
  }
}

此代码运行良好,没有任何问题。
当我没有互联网连接或服务器连接失败时,应用程序会冻结,并出现一个错误文件(如果您在 VS Code 中调试),称为

http_impl.dart
,错误代码片段会出现以下内容像这样:

onError: (error) {
// When there is a timeout, there is a race in which the connectionTask
// Future won't be completed with an error before the socketFuture here
// is completed with a TimeoutException by the onTimeout callback above.
// In this case, propagate a SocketException as specified by the
// HttpClient.connectionTimeout docs.
if (error is TimeoutException) {
  assert(connectionTimeout != null);
  _connecting--;
  _socketTasks.remove(task);
  task.cancel();
  throw SocketException(
      "HTTP connection timed out after $connectionTimeout, "
      "host: $host, port: $port");
}
_socketTasks.remove(task);
_checkPending();
throw error;
});

我尝试从this sourcethis实现,但是当我发出请求但没有连接时,仍然出现这个错误。

如何处理这个问题?
我想要的是,如果 HTTP 出现问题,要么没有连接,要么无法联系服务器,那么我可以发出通知..

我的代码有问题吗? 请帮忙,谢谢

flutter http connection-timeout flutter-http
1个回答
0
投票
  1. 您在代码中重新抛出异常, 您需要在像这样调用此方法的地方捕获异常。

    尝试{ 等待 fetchData(); } 捕获 (e) { // TODO: 处理异常 }

  2. 您可以通过这种方式停止 VS Code 捕获未处理的异常 https://superuser.com/a/1609472

© www.soinside.com 2019 - 2024. All rights reserved.