首页 > 解决方案 > 捕获套接字异常

问题描述

我为 http get 请求使用了一个函数,并且使用正确的 URL 可以正常工作。

但是,如果我将 URL 更改为错误的 URL(以模拟第三方后端的某些更改),我总是在 json.decode 行中遇到异常:Unhandled exception: Socket Exception: Failed host lookup. 'myurl.com' (OS Error: No address associated with hostname, errno = 7)

为什么我的 try/catch 块没有捕捉到这个异常?如果状态码是 200 但我没有收到 SocketException,我如何捕获异常?

  varLookup(String variable) async {
    http.Response response = await http.get('https://myurl.com/${variable}');
    if (response.statusCode == 200) {
      try {
        var jsonResponse = json.decode(response.body);
        return;
      } catch (error) {
        var getError = error;
        return;
      }
    } else {
      print('Status code not 200');
      return;
    }
  }

标签: httpfluttersocketexception

解决方案


推荐阅读