Search code examples
springspring-webfluxspring-webclient

Spring WebClient throw error based on response body


I am using Spring WebClient to call REST API. I want to throw an error based on the response. For example, if there is an error (400) with body

{"error": "error message1 "}

then I want to throw an error with "error message1". Same way if there is an error(400) with the body

{"error_code": "100020"}

then I want to throw an error with error_cde 100020. I want to do it in a non-blocking way.

public Mono<Response> webclient1(...) {

 webClient.post().uri(createUserUri).header(CONTENT_TYPE, APPLICATION_JSON)
                .body(Mono.just(request), Request.class).retrieve()
                .onStatus(HttpStatus::isError, clientResponse -> {
        
                 //Error Handling
                
                }).bodyToMono(Response.class);
}

Solution

  • A body from ClientResponse should be extracted in a reactive way (javadoc) and lambda in onStatus method should return another Mono (javadoc). To sum up, take a look at below example

    onStatus(HttpStatus::isError, response -> response
        .bodyToMono(Map.class)
        .flatMap(body -> {
            var message = body.toString(); // here you should probably use some JSON mapper
            return Mono.error(new Exception(message));
        })
    );