I want to handle a HEAD endpoint so that if the HTTP status is successful, I return true
. If it's 404, I return false
. Else, I want to throw different exceptions.
I currently have the following:
boolean head(String param) {
return webClient.head()
.uri(fromPath(PATH).pathSegment(param))
.exchangeToMono(response -> {
if(response.statusCode().is2xxSuccessful()){
return Mono.just(Boolean.TRUE);
} else if (response.statusCode().equals(NOT_FOUND)){
return Mono.just(Boolean.FALSE);
}
//what to do here?
})
.onErrorMap(this::mapErrorFunction)
.block();
}
My mapErrorFunction
is already in use by other methods, and it's the one I want to use since depending on the raised exception, one thing or another will be done. However, it requires a parameter of type Throwable
which I don't have when reaching the end of the exchangeToMono
block, to I can't do this.mapErrorFunction
at that point.
For the record, the successful and the 404 cases are properly working.
How can I do this? Maybe exchangeToMono
is not the right option here.
The answer is to throw the exception after the if else and let the onErrorMap
method handle it:
boolean head(String param) {
return Boolean.TRUE.equals(webClient.head()
.uri(uri.toUriString())
.exchangeToMono(response -> {
if (response.statusCode().is2xxSuccessful()) {
return Mono.just(Boolean.TRUE);
} else if (response.statusCode().equals(NOT_FOUND)) {
return Mono.just(Boolean.FALSE);
}
return response.createException().flatMap(Mono::error);
})
.onErrorMap(this::mapErrorFunction)
.block());