I want to handle MethodArgumentNotValidException in a Springboot application. My entry point is expecting a valid JSON object. I do intercept the error message correctly:
"message": "JSON parse error: Cannot deserialize value of type `java.util.LinkedHashMap<java.lang.String,java.lang.Object>` from Array value (token `JsonToken.START_ARRAY`); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `java.util.LinkedHashMap<java.lang.String,java.lang.Object>` from Array value (token `JsonToken.START_ARRAY`)\n at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 5, column: 7] (through reference chain: fr.ws.ui.model.request.RequestModel[\"data\"]->java.util.ArrayList[0])",
That's great... Here is my exception handler implementation.
@ExceptionHandler(value = { MethodArgumentNotValidException.class, HttpMessageNotReadableException.class })
public ResponseEntity<ErrorMessage> handleHttpMessageNotReadableException(HttpMessageNotReadableException ex,
WebRequest req) throws JsonProcessingException {
// weird behavior, I got the json but not complete
String output;
try {
output = IOUtils.toString(((ServletWebRequest) req).getRequest().getInputStream(), StandardCharsets.UTF_8);
System.out.println(output);
} catch (IOException e) {
throw new RuntimeException(e);
}
ErrorMessage errorMessage = ErrorMessage.builder()
.operationId(Utils.generateId())
.status(RequestOperationStatus.ERROR.name())
.message(ex.getMessage())
.createdAt(new Date())
.data(output)
.build();
return new ResponseEntity<>(errorMessage, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
}
Now, I want to retrieve the body of my request and I want to parse the content to extract data for building the ErrorMessage body. For this I used org.apache.commons.io
library:
IOUtils.toString(((ServletWebRequest) req).getRequest().getInputStream(), StandardCharsets.UTF_8)
The request contains several properties and a file in Base64 format. It works fine but not totally: I do not retrieve the full request body, I do not get the request body start. My String seems truncated. How can i get the whole request as String ?