如何使用 http 库捕获 SocketException?

How to catch SocketException using the http library?

这个问题已经被其他人指出(比如)。虽然我可能已经明白了原因,但在使用更高级别的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 以便等待回复。这允许您捕获异常(例如,return 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;
  }
}

http

上的 SocketException
 try {

    } on SocketException {

    }

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

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); 的函数。

捕获错误的一种简单方法是像这样使用 catch 错误参数调用 get 方法上的方法。 get 方法的这个方法可以捕获其他类型的错误,而不仅仅是套接字异常。查看下面的代码了解更多

import 'package:http/http.dart';

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,
    },
     ).catchError(error){
    //you can now do your error handling in this block
       });
     }
 }