http - 捕获套接字异常
问题描述
我为 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;
}
}
解决方案
推荐阅读
- matlab - 使用向量而不是循环
- ios - 如何处理 Swift 中 UITableViewCell 中可能存在或不存在的元素?
- java - Maven 不会从谷歌存储库下载 jars
- python-2.7 - 无法使用 Apriori 算法生成规则列表
- c++ - 在接受输入时运行后台循环 (C++)
- machine-learning - 当动作不影响强化学习中的状态时,它叫什么?
- typescript - 为什么类型谓词的类型必须可以分配给它的参数类型?
- python-3.x - 从 .xlsx 创建文件夹结构
- javascript - 对象数组到带有修改的对象
- html - DOM contenteditable 选择父节点