【发布时间】: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