reactive-programmingproject-reactorspring-webclientspring-reactivespring-reactor

How to throw an exception in on error part of reactive Spring WebClient call?


I would like the following method to throw a custom exception if an error occurs:

@Service
public class MyClass {

    private final WebClient webClient;

    public MatcherClient(@Value("${my.url}") final String myUrl) {
        this.webClient = WebClient.create(myUrl);
    }

    public void sendAsync(String request) {

        Mono<MyCustomResponse> result = webClient.post()
            .header(HttpHeaders.CONTENT_TYPE, "application/json")
            .body(BodyInserters.fromObject(request))
            .retrieve()
            .doOnError(throwable -> throw new CustomException(throwable.getMessage()))
            .subscribe(response -> log.info(response));

    }

}

I have also set up a unit test expecting the CustomException to be thrown. Unfortunately the test fails and the Exception is kind of wrapped into a Mono object. Here also the test code for reference:

@Test(expected = CustomException.class)
public void testSendAsyncRethrowingException() {
    MockResponse mockResponse = new MockResponse()
        .setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
        .setResponseCode(500).setBody("Server error");
    mockWebServer.enqueue(mockResponse);

    matcherService.matchAsync(track);
}

I'm using the MockWebServer to mock an error in the test.

So, how should I implement the doOnError or onError part if the call in order to make my method really to throw an exception?


Solution

  • Instead of using doOnError I swiched to subscribe method accepting also an error consumer:

    Mono<MyCustomResponse> result = webClient.post()
                .header(HttpHeaders.CONTENT_TYPE, "application/json")
                .body(BodyInserters.fromObject(request))
                .retrieve()
                .subscribe(response -> log.info(response),
                           throwable -> throw new CustomException(throwable.getMessage()));
    

    This documentation helps a lot: https://projectreactor.io/docs/core/release/reference/index.html#_error_handling_operators