18

I use this code for REST API requests.

WebClient.Builder builder = WebClient.builder().baseUrl(gatewayUrl);
ClientHttpConnector httpConnector = new ReactorClientHttpConnector(opt -> opt.sslContext(sslContext));
builder.clientConnector(httpConnector);

How I can add connection exception handler? I would like to implement some custom logic? Is this feature easy to implement?

Peter Penzov
  • 1,126
  • 134
  • 430
  • 808
  • 1
    Possible duplicate of [Set connection timeout using Spring Webflux Reactive WebClient](https://stackoverflow.com/questions/48096573/set-connection-timeout-using-spring-webflux-reactive-webclient) – Brian Clozel Jul 02 '18 at 16:32

1 Answers1

26

If I understand your question in the context of failing the connection because of SSL credentials, then you should see the connection exception manifest itself on the REST response. You can take care of that exception via the Flux result you get on WebClient.ResponseSpec#onStatus. The docs for #onStatus says:

Register a custom error function that gets invoked when the given HttpStatus predicate applies. The exception returned from the function will be returned from bodyToMono(Class) and bodyToFlux(Class). By default, an error handler is register that throws a WebClientResponseException when the response status code is 4xx or 5xx.

Take a look at this example:

Mono<Person> result = client.get()
            .uri("/persons/{id}", id).accept(MediaType.APPLICATION_JSON)
            .retrieve()
            .onStatus(HttpStatus::is4xxServerError, response -> ...) // This is in the docs there but is wrong/fatfingered, should be is4xxClientError
            .onStatus(HttpStatus::is5xxServerError, response -> ...)
            .bodyToMono(Person.class);

Similarly for your question, the connection error should manifest itself after the call gets made and you can customize how it gets propogated in the reactive pipeline:

Mono<Person> result = client.get()
            .uri("/persons/{id}", id).accept(MediaType.APPLICATION_JSON)
            .retrieve()
            .onStatus(HttpStatus::is4xxClientError, response -> {
                 ... Code that looks at the response more closely...
                 return Mono.error(new MyCustomConnectionException());
             })
            .bodyToMono(Person.class);

Hope that helps.

Dovmo
  • 8,121
  • 3
  • 30
  • 44
  • 4
    How can we log the response also here?Along with exception? – Rocky4Ever Aug 24 '20 at 18:30
  • @Rocky4Ever , I think you either need to use `.exchange()` or instead of `.retrieve()` or to implement a global error handler to catch the exceptions and log them, before re-throwing them if wanted. – Hamid Sep 15 '20 at 21:57