title: How to deal with exception when connection lost happens to Spring WebClient
body: <p>I am using Spring WebClient to receive Server Sent Event. When my server shuts down, I got the following exception stack:</p>
  
  <pre><code>[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
  </code></pre>
  
  <p>It is quite obvious in the deep somewhere of WebClient, the Netty caught the exception. However, my question is: how can I catch it so that I can gracefully deal with it.</p>
  
  <p>My code:</p>
  
  <pre><code>final Flux&lt;Object&gt; stream = WebClient.builder()
              .baseUrl("http://localhost:8080/ssp/common/v1/eventstream")
              .build()
              .get()
              .retrieve()
              .bodyToFlux(ServerSentEvent.class)
              .flatMap(e -&gt; Mono.justOrEmpty(e.data()))
              .repeat();
  
      stream.doOnError(e -&gt; System.out.println(e));
      stream.subscribe(e -&gt; processEvent(e));
  </code></pre>
  
  <p>The stream.doOnError() doesn't help for this case. With M. Deinum's comment, I modified the code:</p>
  
  <pre><code>final Flux&lt;Object&gt; stream = WebClient.builder()
              .baseUrl("http://localhost:8080/ssp/common/v1/eventstream")
              .build()
              .get()
              .retrieve()
              .bodyToFlux(ServerSentEvent.class)
              .flatMap(e -&gt; Mono.justOrEmpty(e.data()))
              .doOnError(e -&gt; System.out.println("haha"))
              .repeat();
  
      stream.subscribe(e -&gt; processEvent(e));
  </code></pre>
  
  <p>Then, it is getting a bit better. I got the "haha" printed but I still got the exception stack (a bit shorter):</p>
  
  <pre><code>[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
  </code></pre>