我想实现一个与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)
如何才能捕捉到这种过度行为来进行重新连接?
发布于 2022-03-04 22:01:16
您需要await
try
catch
块中的响应以捕获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
}
}
发布于 2022-03-07 09:55:55
感谢7 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?
}
}
https://stackoverflow.com/questions/70169072
复制相似问题