We have a spring boot app and our controller expects an XML Document element in one of our end points:
@PostMapping(value = "/api/v1/do-stuff",
consumes = APPLICATION_XML_VALUE,
produces = APPLICATION_XML_VALUE)
public ResponseEntity<JAXBElement<my.company.stuff.resposnse.Document>> doStuff(
@RequestBody JAXBElement<my.company.stuff.request.Document> requestBody,
Principal principal) throws Exception {
// Doing some suff here and returning the result
return stuffService.doStuff(...);
}
We have our own instance of Jaxb2Marshaller where we set the schemas for both request document and response document to be used for marshalling and un-marshalling between request and response bodies and our domain objects. When the request comes the spring boot framework will do the conversion between the request body and and the domain request document. Sometimes the request body does not pass XSD schema validation and such it does not even reach our controller.
The exception thrown is passed to our custom extension of org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler
where we would like to create the most meaningful error response for our application clients:
@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {
// Getting access to the request body would be very beneficial here
}
Our issue is that sometimes the exception passed to our handler does not have enough details and we would like to be able to access the request body in order to be able to customise our response to the client. However, the input stream of the request is no longer accessible because it was already read from part of the schema validation (conversion) processing so any attempt to access it this way fails.
On the other hand whaat we are trying to achieve is very common sense and just wondering if we took the wrong approach and what would be a better design to achieve the same thing. Changing the controller to expect a plain text and validate and convert it to the request document inside the controller is not really an option.
Thank you in advance or your inputs.