如何在dart中捕获http.send中的“Connection closed while receiving data”?

wvmv3b1j  于 4个月前  发布在  其他
关注(0)|答案(2)|浏览(34)

我想在https://pub.dev/packages/flutter_client_sse包中实现一个重新连接逻辑。http连接保持打开状态并监听服务器端事件。当连接由于某种原因丢失时,客户端应该尝试重新连接。连接丢失时会抛出一个异常,但我无法捕获它。
建立连接的代码:

try {
        _client = http.Client();
        var request = http.Request("GET", Uri.parse(url));
        //Adding headers to the request
        request.headers["Cache-Control"] = "no-cache";
        request.headers["Accept"] = "text/event-stream";

        Future<http.StreamedResponse> response = _client.send(request);
        response.onError((e, s) {
          Log.e("ERROR!");
          throw e.cause ?? e;
        });
        response.catchError((e) => Log.e("ERROR!"));
        response.asStream().listen((data) {
         ... 
        });
     } catch(e) {
         Log.e("ERROR!");
     }

字符串
当连接丢失时,会抛出一个异常:

[ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: Connection closed while receiving data
E/flutter (24389): #0      IOClient.send.<anonymous closure> (package:http/src/io_client.dart:49:13)
E/flutter (24389): #1      _invokeErrorHandler (dart:async/async_error.dart:45:24)
E/flutter (24389): #2      _HandleErrorStream._handleError (dart:async/stream_pipe.dart:272:9)
E/flutter (24389): #3      _ForwardingStreamSubscription._handleError (dart:async/stream_pipe.dart:157:13)
E/flutter (24389): #4      _HttpClientResponse.listen.<anonymous closure> (dart:_http/http_impl.dart:712:16)
E/flutter (24389): #5      _rootRunBinary (dart:async/zone.dart:1378:47)
E/flutter (24389): #6      _CustomZone.runBinary (dart:async/zone.dart:1272:19)
E/flutter (24389): #7      _CustomZone.runBinaryGuarded (dart:async/zone.dart:1178:7)


我怎么能抓住这个借口做重新连接?

7rtdyuoh

7rtdyuoh1#

你需要awaittrycatch块中的响应来捕获http错误,我修改了你的代码一点
第一个try

try {
    _client = http.Client();
    var request = http.Request("GET", Uri.parse(url));
    //Adding headers to the request
    request.headers["Cache-Control"] = "no-cache";
    request.headers["Accept"] = "text/event-stream";

    // wait for the response
    http.StreamedResponse response =await _client.send(request);

    // then listen to the stream
    response.stream.listen((data) {}, onError: (e, s) {});
    }

字符串
第二个catch
你需要检查catch块上的错误类型,在你的例子中是ClientException

catch (e) {
    if (e is ClientException) {
      // handel error
    }
  }


然后您可以检查错误消息

if (e is ClientException) {
  if (e.message == 'Connection closed while receiving data') {
    // handel error
  }
}

qlzsbp2j

qlzsbp2j2#

感谢7mada的回复。这是我用他的解决方案实现的:

Future<void> connect(String path) async {
    try {
      final _client = http.Client();

      final request = http.Request('GET', Uri.parse(baseUrl + path));

      final response = await _client.send(request);

      response.stream.listen(
        (data) {
          _streamController.add(utf8.decode(data));
        },
        onError: (e, s) {
          if (e is http.ClientException) {
            connect(path);
          }
        },
      );
    } on Exception catch (_) {
      // What errors could happen here?
    }
  }

字符串

相关问题