11

This problem has already been pointed out by others (like here). Althought I may have understood the cause, I still haven't found a solution when using the higher-level http library. For example:

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,
    },
  ));
}

I can't find a way to catch a SocketException that is thrown, for example, if the host can't be reached (in my case, wrong host ip). I have tried wrapping the await in try/catch, or using Future.catchError.

This is a stacktrace of the exception:

[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)
4

3 回答 3

16

您可以更改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;
  }
}
于 2018-07-13T14:39:22.657 回答
3

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

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()}");
  }
}

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

于 2021-04-16T14:19:17.843 回答
0

http 上的 SocketException

 try {

    } on SocketException {

    }
于 2020-11-06T08:20:31.167 回答