捕获套接字异常

时间:2020-08-10 14:05:13

标签: http flutter socketexception

我对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;
    }
  }

0 个答案:

没有答案
相关问题