In a Spring Boot application, I'm using WebClient
to invoke a POST request to a remote application. The method currently looks like this:
// Class A
public void sendNotification(String notification) {
final WebClient webClient = WebClient.builder()
.defaultHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE)
.build();
webClient.post()
.uri("http://localhost:9000/api")
.body(BodyInserters.fromValue(notification))
.retrieve()
.onStatus(HttpStatus::isError, clientResponse -> Mono.error(NotificationException::new))
.toBodilessEntity()
.block();
log.info("Notification delivered successfully");
}
// Class B
public void someOtherMethod() {
sendNotification("test");
}
The use case is: A method in another class calls sendNotification
and should handle any error, i.e. any non 2xx status or if the request couldn't even be sent.
But I'm struggling with the concept of handling errors in the WebClient
. As far as I understood, the following line would catch any HTTP status other than 2xx/3xx and then return a Mono.error
with the NotificationException
(a custom exception extending Exception
).
onStatus(HttpStatus::isError, clientResponse -> Mono.error(NotificationException::new))
But how could someOtherMethod()
handle this error scenario? How could it process this Mono.error
? Or how does it actually catch the NotificationException
if sendNotification
doesn't even throw it in the signature?