Home > Mobile >  Spring WebFlux - how to catch conflict exception
Spring WebFlux - how to catch conflict exception

Time:09-30

I have a method like below:

public String createFolder3(String folderName, String parentFolderId)
{
    String requestJson = "{\"name\": "   folderName   "}";
    return webClient.post()
        .uri("/the/uri/goeshere/"   parentFolderId   "/children")
        .body(Mono.just(requestJson), String.class)
        .retrieve()
        .onStatus(httpStatus -> HttpStatus.CONFLICT.equals(httpStatus),
                clientResponse -> Mono.error(new Exception("Some Conflict Occurred")))
        .bodyToMono(String.class).block();
}

But everytime I get the below (huge, I cut it short for brevity) exception. I don't want to display this huge exception on the server side console. What I am doing wrong or missing here?

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'processJob': Invocation of init method failed; nested exception is reactor.core.Exceptions$ReactiveException: java.lang.Exception: Some Error Occurred
.....
Caused by: reactor.core.Exceptions$ReactiveException: java.lang.Exception: Some Error Occurred
.....
Error has been observed at the following site(s):
    |_ checkpoint ⇢ 409 from POST http:.....
....

CodePudding user response:

If you want the response body to be returned in case of a 409, you could catch WebClientResponseException:

.retrieve()
.bodyToMono(String.class)
.onErrorResume(
  WebClientResponseException.class,
  e -> {
    if (e.getStatusCode() == HttpStatus.CONFLICT) {
      // log
      return Mono.just(e.getResponseBodyAsString());
    }
    return Mono.error(e);
  }
)
  • Related