如何使用http库捕获SocketException?

时间:2018-07-13 13:01:16

标签: dart flutter dart-http

其他人已经指出了这个问题(例如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,
    },
  ));
}

例如,如果无法访问主机(在我的情况下,错误的主机ip),我无法找到捕获抛出的SocketException的方法。 我尝试将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)

3 个答案:

答案 0 :(得分:3)

您可以将int portNum = 0; string yourPortStringFormatted = Regex.Replace(yourPortString , @"\t|\n|\r", ""); bool isSuccees= Int32.TryParse(string.IsNullOrEmpty(yourPortStringFormatted) ? "0" : yourPortStringFormatted , out portNum ); 更改为login,以便等待响应。这样就可以捕获异常(例如,返回async而不是null)。

Response

答案 1 :(得分:0)

http上的SocketException

 try {

    } on SocketException {

    }

答案 2 :(得分:0)

您可以检查异常的类型并相应地处理它,例如:

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) {
    if(e is SocketException){
       //treat SocketException
       print("Socket exception: ${e.toString()}");
    }
    else if(e is TimeoutException){
       //treat TimeoutException
       print("Timeout exception: ${e.toString()}");
    }
    else print("Unhandled exception: ${e.toString()}");
  }
}

最好制作一个错误处理程序库,这样您就可以在 catch 块上调用 handleException(e); 之类的函数。