Search code examples
spring-bootspring-webclient

Where do I place "doOnError" in my webclient call?


I have a webclient call that looks like :-

return this.webClient.post()
                .uri(url)
                .accept(MediaType.APPLICATION_JSON)
                .body(BodyInserters.fromValue(request))
                .retrieve()
                .bodyToMono(Reponse.class)
                .doOnError(err -> {
                    throw new UserDefinedException();
                })
                .block();

Would it make a difference if i placed "doOnError()" before bodyToMono/retreive/ and so on..


Solution

  • The expected way to transform an error signal to a custom exception is to use onErrorMap operator:

    return this.webClient.post()
                    .uri(url)
                    .accept(MediaType.APPLICATION_JSON)
                    .body(BodyInserters.fromValue(request))
                    .retrieve()
                    .bodyToMono(Reponse.class)
                    .onErrorMap(err -> new UserDefinedException())
                    .block();
    

    onErrorMap operator catch any Mono errors and map them to a custom exception.

    bodyToMono, transform the chain to a Mono in the success case, so it could be after onErrorMap.