首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在dart中捕获来自http.send的“在接收数据时关闭的连接”?

如何在dart中捕获来自http.send的“在接收数据时关闭的连接”?
EN

Stack Overflow用户
提问于 2021-11-30 12:03:11
回答 2查看 809关注 0票数 1

我想实现一个与https://pub.dev/packages/flutter_client_sse包重新连接的逻辑。http连接保持打开状态,并侦听服务器端事件。当连接因某种原因丢失时,客户端应该尝试重新连接。一旦连接丢失,就会引发异常,但我无法捕捉它。

构建连接的代码:

代码语言:javascript
运行
复制
     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!");
     }   

当连接丢失时,将引发异常:

代码语言:javascript
运行
复制
[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)

如何才能捕捉到这种过度行为来进行重新连接?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-03-04 22:01:16

您需要await try catch块中的响应以捕获http错误,我修改了您的代码。

第一try

代码语言:javascript
运行
复制
    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

代码语言:javascript
运行
复制
catch (e) {
    if (e is ClientException) {
      // handel error
    }
  }

然后,您可以检查错误消息。

代码语言:javascript
运行
复制
if (e is ClientException) {
  if (e.message == 'Connection closed while receiving data') {
    // handel error
  }
}
票数 1
EN

Stack Overflow用户

发布于 2022-03-07 09:55:55

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

代码语言:javascript
运行
复制
  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?
    }
  }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70169072

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档