0

I never worked with WebClient before, but I have to use it to send a Post request to an external url. After that I check the response status, and if it's 204 I'll continue with the process, but if the status is some errorcode I should send back the received error message from the ResponseEntity. However if the request receives an Error code, the webclient sends an exception, instead of returning the ResponseEntity. The code looks like this:

Public ResponseEntity<Void> post(String uri, User value)
return webClient.post()
.uri(uri)
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(value)
.retreive()
.toEntity(Void.class)
.timeout(properties.getTimeout)
.retryWhen(retry
    .filter(this::filterError)
    .doBefore(log.error("error message...")))
.block();

I expect WebClient to send back the full responseEntity and not throwing and exception. I tried to look for sollution, but almost every post is returning the body only, and using bodyToMono. I don't want that.

I tried to use onStatus like this, but didn't work:

Public ResponseEntity<Void> post(String uri, User value)
return webClient.post()
.uri(uri)
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(value)
.retreive()
.onStatus(HttpStatus::isError, clientResponse ->
    clientResponse.bodyToMono(String.class)
        .flatMap(error -> Mono.error(new RuntimeException(error)))
.toEntity(Void.class)
.timeout(properties.getTimeout)
.retryWhen(retry
    .filter(this::filterError)
    .doBefore(log.error("error message...")))
.block();

I also wanted to use onErrorResume, but that returns Mono<ResponseEntity> and I have no idea how to work with that.

Also tried using .exchange() instead of retreive() but I saw it's deprecated now, so I rolled back to retreive.

Shell I just wrap the code where I use the post request to a try catch block and catch WebClientResponseException.class ? That might be ugly and will fail during code review. Any other suggestions? Using Java17.

EDIT:

Modified the onStatus and now I'm able to get the statuscode at least, however not sure how to add the error message also. Modified code:

Public ResponseEntity<Void> post(String uri, User value)
return webClient.post()
.uri(uri)
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(value)
.retreive()
.onStatus(HttpStatus::isError, clientResponse ->
    Mono.empty)
.toEntity(Void.class)
.timeout(properties.getTimeout)
.retryWhen(retry
    .filter(this::filterError)
    .doBefore(log.error("error message...")))
.block();
Zoltan514
  • 1
  • 1

0 Answers0