我正在使用Spring WebClient接收服务器已发送事件。当服务器关闭时,出现以下异常堆栈:
[reactor.ipc.netty.channel.ChannelOperations:283] - [HttpClient] Error processing connection. Requesting close the channel
java.io.IOException: An existing connection was forcibly closed by the remote host
[reactor-http-nio-4] [] [] [reactor.ipc.netty.channel.ContextHandler:283] - Error cannot be forwarded to user-facing Mono
java.io.IOException: An existing connection was forcibly closed by the remote host
[io.netty.channel.AbstractChannelHandlerContext:146] - An exception '{}' [enable DEBUG level for full stacktrace] was thrown by a user handler's exceptionCaught() method while handling the following exception:
java.io.IOException: An existing connection was forcibly closed by the remote host
在WebClient的深处很明显,Netty捕获了异常。但是,我的问题是:如何捕获它,以便可以优雅地处理它。
我的代码:
final Flux<Object> stream = WebClient.builder()
.baseUrl("http://localhost:8080/ssp/common/v1/eventstream")
.build()
.get()
.retrieve()
.bodyToFlux(ServerSentEvent.class)
.flatMap(e -> Mono.justOrEmpty(e.data()))
.repeat();
stream.doOnError(e -> System.out.println(e));
stream.subscribe(e -> processEvent(e));
stream.doOnError()在这种情况下无济于事。在M. Deinum的评论下,我修改了代码:
final Flux<Object> stream = WebClient.builder()
.baseUrl("http://localhost:8080/ssp/common/v1/eventstream")
.build()
.get()
.retrieve()
.bodyToFlux(ServerSentEvent.class)
.flatMap(e -> Mono.justOrEmpty(e.data()))
.doOnError(e -> System.out.println("haha"))
.repeat();
stream.subscribe(e -> processEvent(e));
然后,它会变得更好一点。我打印了“哈哈”字样,但仍然有异常堆栈(短了一点):
[reactor.ipc.netty.channel.ChannelOperations:283] - [HttpClient] Error processing connection. Requesting close the channel
java.io.IOException: An existing connection was forcibly closed by the remote host
[reactor-http-nio-4] [] [] [reactor.ipc.netty.channel.ContextHandler:283] - Error cannot be forwarded to user-facing Mono
java.io.IOException: An existing connection was forcibly closed by the remote host