【问题标题】:unhandled socket exception with no internet connection when i set timeout duration当我设置超时持续时间时,未处理的套接字异常没有互联网连接
【发布时间】:2019-07-24 12:27:12
【问题描述】:

我使用简单的方法从 Internet 'http get request' 获取一些数据:

     `Future<UserModel> getUser(int userId) async {
       UserModel user;
       try {
            final response = await http.get(
             "$_baseUrl/users/$userId",
           )
             .timeout(Duration(seconds: 5))

            ;
         user = userModelFromJson(response.body);
       return user;
      } on TimeoutException catch (e) {
       print('$e in authentication service');
     throw e;
      } on SocketException catch (e) {
     print('$e in authentication service');
     throw e;
     } catch (e) {
     print('$e in authentication service');
    throw e;
      }
      }` 

但是当我没有互联网连接时,它会显示错误:

 `Exception has occurred.
    SocketException (SocketException: Failed host lookup: 
    'jsonplaceholder.typicode.com' (OS Error: No address associated with 
    hostname, errno = 7))`

每当我删除 .timeout(Duration(seconds:5)) 时,代码都能完美运行, 但是在长时间(15-20)秒后捕获了套接字异常以表明没有互联网连接这就是我使用超时的原因,我尝试使用多个包(http中间件,http助手,重试),我尝试使用http .client 并在 finally 块中关闭它,发生同样的错误,应用程序崩溃

the image shows the error when the socket exception is thrown and unhandled

它按预期捕获了超时异常,但又过了 10-15 秒后,它抛出了一个已处理的套接字异常,为什么它会抛出这个套接字异常,我该怎么做才能避免这种情况?

【问题讨论】:

  • 但是你真的能在你的 try / catch 中捕捉到异常吗?看来我和你有同样的错误,但对我来说,这个错误只被 VSCode 捕获(根据你链接的图像)
  • @Gpack 是对的,在 android studio 尝试你的代码它会起作用

标签: flutter dart unhandled-exception socketexception timeoutexception


【解决方案1】:

如果你想用 http 包实现超时,可以这样做:

import 'dart:io';

import 'package:http/http.dart' as http;
import 'package:http/io_client.dart' as http;

Future<void> login(String email, String password) async {
    final ioClient = HttpClient();
    client.connectionTimeout = const Duration(seconds: 5);
    final body = { 'email': email, 'password': password };
    final client = http.IOClient(ioClient);
    http.Response res;
    try {
      res = await client
        .post(
          '$url/login',
          headers: {'Content-Type': 'application/json'},
          body: jsonEncode(body));
    } on SocketException catch (e) {
      // Display an alert, no internet
    } catch (err) {
      print(err);
      return null;
    }

    // Do something with the response...
}

【讨论】:

    【解决方案2】:

    您应该考虑使用 HTTP 包 https://pub.dev/packages/http 因为它有助于清理代码并有助于错误处理。

    这是一个使用包的 GET 请求示例:

    await http.get(url).then((response) async {
     // DO SOMETHING HERE
    });
    

    response.body 是您的数据。 response.statusCode 是你的http状态码(200、404、500等)

    https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

    这是一个带有数据的发布请求:

    var data = {
          "dataset1": {
            "key1": "value",
            "key2": "value",
          },
        };
    await http.post(url,
      body: jsonEncode(data),
      headers: {'content-type': 'application/json'}).then((response) async {
        // DO SOMETHING HERE
    });
    

    【讨论】:

    • 这就是我已经完成的,http.get() 部分来自 http 包,问题是当我使用 get 方法超时时未处理的套接字异常
    • 糟糕,对不起!我没有正确理解你的问题!
    • 没关系,有什么想法请分享一下
    猜你喜欢
    • 1970-01-01
    • 2021-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-21
    • 1970-01-01
    • 2014-10-10
    • 1970-01-01
    相关资源
    最近更新 更多