gpt4 book ai didi

asynchronous - net不在时如何处理socket异常?

转载 作者:IT王子 更新时间:2023-10-29 07:22:48 25 4
gpt4 key购买 nike

如果网络不存在,我想显示一个错误屏幕。我没有使用 connectivity包,因为我不想连续检查。我只想在调用后端 api 并显示屏幕时处理异常。我无法捕捉到异常。

我找到了 this问题和this有关套接字异常的问题,但似乎没有任何帮助。

这就是我调用后端 api 的方式 -

callBackendApi() async {
try {
http.Response response = await Future.value(/*api call here*/)
.timeout(Duration(seconds: 90), onTimeout: () {
print('TIME OUT HAPPENED');
});
} catch (exception) {
Fluttertoast.showToast(msg: 'Check internet connection.');
print('Error occurred' + exception.toString());
}
}

最佳答案

我使用 dio像这样:

try {

var formData = FormData.from(Map<String, dynamic>.from(data));

var response = await dio.post(
uri,
data: formData,
);
jsonResponse = json.decode(response.data);
} on DioError catch (e) {

if (DioErrorType.RECEIVE_TIMEOUT == e.type ||
DioErrorType.CONNECT_TIMEOUT == e.type) {
throw CommunicationTimeoutException(
"Server is not reachable. Please verify your internet connection and try again");
} else if (DioErrorType.RESPONSE == e.type) {
// 4xx 5xx response
// throw exception...
} else if (DioErrorType.DEFAULT == e.type) {
if (e.message.contains('SocketException')) {
throw CommunicationTimeoutException('blabla');
}
} else {
throw CommunicationException("Problem connecting to the server. Please try again.");
}
}

关于asynchronous - net不在时如何处理socket异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54762255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com