How do you retrieve the response body when trying to throw an exception based on the returned status code? For instance, lets say I want to throw an exception and reject HTTP 201.
client.post().exchange().doOnSuccess(response -> {
if (response.statusCode().value() == 201) {
throw new RuntimeException();
}
}
How can I populate the exception with the response's body so I can throw a detailed WebClientResponseException
?
Should I be using a different method to test the response status code?
edit: I am trying to duplicate the following functionality while using exchange()
instead.
client.get()
.retrieve()
.onStatus(s -> !HttpStatus.CREATED.equals(s),
MyClass::createResponseException);
//MyClass
public static Mono<WebClientResponseException> createResponseException(ClientResponse response) {
return response.body(BodyExtractors.toDataBuffers())
.reduce(DataBuffer::write)
.map(dataBuffer -> {
byte[] bytes = new byte[dataBuffer.readableByteCount()];
dataBuffer.read(bytes);
DataBufferUtils.release(dataBuffer);
return bytes;
})
.defaultIfEmpty(new byte[0])
.map(bodyBytes -> {
String msg = String.format("ClientResponse has erroneous status code: %d %s", response.statusCode().value(),
response.statusCode().getReasonPhrase());
Charset charset = response.headers().contentType()
.map(MimeType::getCharset)
.orElse(StandardCharsets.ISO_8859_1);
return new WebClientResponseException(msg,
response.statusCode().value(),
response.statusCode().getReasonPhrase(),
response.headers().asHttpHeaders(),
bodyBytes,
charset
);
});
}