对于Spring WebFlux的WebClient,如何捕获Netty的异常(例如ProxyConnectException)

时间:2019-05-08 11:03:28

标签: spring-webflux

我想在应用程序中将Apache HttpComponents Client更改为Spring WebFlux的WebClient。但是我无法捕获来自Netty的异常,例如io.netty.handler.proxy.ProxyConnectException

我尝试使用doOnError运算符,但是对于这些异常,无​​法捕获它们。

var timeout = Duration.ofSeconds(3);
        if (proxy != null) {
            HttpClient httpClient = HttpClient.create()
                .tcpConfiguration(tcpClient ->
                    tcpClient.proxy(py -> py.type(ProxyProvider.Proxy.HTTP).host(proxy.getHost()).port(proxy.getPort()).username(proxy.getUser()).password(tmp -> proxy.getPass())).doOnConnected(conn -> conn
                        .addHandlerLast(new ReadTimeoutHandler((int) (timeout.toSeconds() / 2)))
                        .addHandlerLast(new WriteTimeoutHandler((int) (timeout.toSeconds() / 2)))));
            ReactorClientHttpConnector connector = new ReactorClientHttpConnector(httpClient);

            ExchangeStrategies strategies = ExchangeStrategies
                .builder()
                .codecs(clientDefaultCodecsConfigurer -> {
                    clientDefaultCodecsConfigurer.defaultCodecs().jackson2JsonEncoder(new Jackson2JsonEncoder(objectMapper, MediaType.APPLICATION_JSON));
                    clientDefaultCodecsConfigurer.defaultCodecs().jackson2JsonDecoder(new Jackson2JsonDecoder(objectMapper, MediaType.APPLICATION_JSON));

                }).build();

            WebClient webClient = WebClient
                .builder()
                .exchangeStrategies(strategies)
                .clientConnector(connector)
                .build();
            ClientResponse httpException = ClientResponse.create(org.springframework.http.HttpStatus.REQUEST_TIMEOUT).build();


      webClient
      .get()
      .uri("my_uri")
      .accept(MediaType.ALL)
      .header("my_header_key", "my_header_value")
      .exchange().doOnError(ProxyConnectException.class, throwable -> {
                    logger.warn("ProxyConnectException");
                })
      .onErrorReturn(httpException)
      .doOnError(ConnectTimeoutException.class, e -> {
                    logger.warn("ConnectTimeoutException");
                })
      .doOnError(ReadTimeoutException.class, e -> {
                    logger.warn("ReadTimeoutException");
                })
      .doOnError(SSLException.class, e -> {
                    logger.warn("SSLException");
                })
      .doOnError(Exception.class, e -> {
                    logger.warn("Exception");
                })
      .onErrorReturn(httpException)
      .block();

我想要的只是打印日志并返回httpException对象。但是结果不仅是我期望的结果,打印了我的日志,还返回了我的对象,但是我还可以看到一些异常信息,例如有没有办法避免这些异常?

io.netty.handler.proxy.ProxyConnectException: http, none, /XXXX:XX => XXXX:XX, timeout
    at io.netty.handler.proxy.ProxyHandler$2.run(ProxyHandler.java:201)
    at io.netty.util.concurrent.PromiseTask$RunnableAdapter.call(PromiseTask.java:38)
    at io.netty.util.concurrent.ScheduledFutureTask.run(ScheduledFutureTask.java:127)
    at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:163)
    at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:404)
    at io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:335)
    at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:897)
    at java.base/java.lang.Thread.run(Thread.java:834)
ERROR [reactor-http-epoll-5] HttpClientConnect --- [id: 0x3610bfd0, L:/XXXX:XX ! R:XXXX/XXXX:XX] The connection observed an error
java.nio.channels.ClosedChannelException: null
    at io.netty.handler.ssl.SslHandler.channelInactive(...)(Unknown Source)```

1 个答案:

答案 0 :(得分:0)

阅读源代码后,我发现该异常是由 reactor.netty.http.client 打印的。而且我确信已经捕获了该异常,因此整个异常堆栈信息都没有用对我来说。我要做的只是禁用日志。

<logger name="reactor.netty.http.client" level="OFF"/>