gpt4 book ai didi

dart - 如何使用 http 库捕获 SocketException?

转载 作者:IT老高 更新时间:2023-10-28 12:44:36 26 4
gpt4 key购买 nike

其他人已经指出了这个问题(如 here )。尽管我可能已经理解了原因,但在使用更高级别的 http 库时,我仍然没有找到解决方案。例如:

import 'package:http/http.dart';

// yes, pwd is String, it's just a test...
Future<Response> login(String user, String pwd) {
final authHeader = encodeBasicCredentials(user, pwd);
return get(
'http://192.168.0.100:8080/login',
headers: <String, String>{
HttpHeaders.AUTHORIZATION: authHeader,
},
));
}

我找不到捕获抛出的 SocketException 的方法,例如,如果无法访问主机(在我的情况下,主机 ip 错误)。我尝试将 await 包装在 try/catch 中,或使用 Future.catchError

这是异常的堆栈跟踪:

[ERROR:topaz/lib/tonic/logging/dart_error.cc(16)] Unhandled exception:
E/flutter ( 4036): SocketException: OS Error: Connection refused, errno = 111, address = 192.168.0.100, port = 35588
E/flutter ( 4036): #0 IOClient.send (package:http/src/io_client.dart:30:23)
E/flutter ( 4036): <asynchronous suspension>
E/flutter ( 4036): #1 BaseClient._sendUnstreamed (package:http/src/base_client.dart:171:38)
E/flutter ( 4036): <asynchronous suspension>
E/flutter ( 4036): #2 BaseClient.get (package:http/src/base_client.dart:34:5)
E/flutter ( 4036): #3 get.<anonymous closure> (package:http/http.dart:47:34)
E/flutter ( 4036): #4 _withClient (package:http/http.dart:167:20)
E/flutter ( 4036): <asynchronous suspension>
E/flutter ( 4036): #5 get (package:http/http.dart:47:3)

最佳答案

您可以将 login 更改为 async 以便您可以等待响应。这允许您捕获异常(例如,返回 null 而不是 Response)。

Future<Response> login(String user, String pwd) async {
final String authHeader = encodeBasicCredentials(user, pwd);
try {
return await get(
'http://192.168.0.100:8080/login',
headers: {
HttpHeaders.AUTHORIZATION: authHeader,
},
);
} catch (e) {
print(e);
return null;
}
}

关于dart - 如何使用 http 库捕获 SocketException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51325758/

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