如果应用程序无法连接到服务器(例如,如果服务器已关闭),但我想捕获异常,但目前还不确定如何并且没有成功。
我的代码:
static Future<String> communicate(String img, String size) async
{
String request = size.padLeft(10, '0') + img;
Socket _socket;
await Socket.connect(ip, 9933).then((Socket sock)
{
_socket = sock;
}).then((_)
{
//Send to server
_socket.add(ascii.encode(request));
return _socket.first;
}).then((data)
{
//Get answer from server
response = ascii.decode(base64.decode(new String.fromCharCodes(data).trim()));
});
return response;
}
函数调用:
var ans = await communicate(bs64Image, size);
答案 0 :(得分:2)
如果请求失败,请尝试使用SocketException
import 'dart:io';
try {
response = await get(url);
} on SocketException catch (e) {
return e;
}
答案 1 :(得分:1)
通常,您使用async / await处理此类错误:
try {
// code that might throw an exception
}
on Exception1 {
// exception handling code
}
catch Exception2 {
// exception handling
}
finally {
// code that should always execute; irrespective of the exception
}
在您的情况下,您应该尝试以下操作:
try {
var ans = await communicate(bs64Image, size);
}
catch (e){
print(e.error);
}
finally {
print("finished with exceptions");
}
答案 2 :(得分:0)
要处理异步函数中的错误,请使用 try-catch:
在异步函数中,您可以像在同步代码中一样编写 try-catch clauses。
运行以下示例以查看如何处理来自 asynchronous
函数的错误
Future<void> printOrderMessage() async {
try {
var order = await fetchUserOrder();
print('Awaiting user order...');
print(order);
} catch (err) {
print('Caught error: $err');
}
}
Future<String> fetchUserOrder() {
// Imagine that this function is more complex.
var str = Future.delayed(
Duration(seconds: 4),
() => throw 'Cannot locate user order');
return str;
}
Future<void> main() async {
await printOrderMessage();
}