When building a REST API with Spring Boot a HttpMessageNotReadableException seems to be thrown when for example the JSON request body is incorrect and thus cannot be parsed.
Suppose a REST API endpoint expects the following JSON request body:
{ "email": "myemail@email.com" }
However, instead the following JSON request body is provided (missing quotation mark):
{ "email: "myemail@email.com" }
The result is the following exception message:
JSON parse error: Unexpected character ('m' (code 109)): was expecting a colon to separate field name and value; nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character ('m' (code 109)): was expecting a colon to separate field name and value\n at [Source: (PushbackInputStream); line: 2, column: 15]
Now, this exception message contains useful information such as the unexpected character, what character was expected instead, and the location. However the exception message also leaks implementation details which is undesirable for my use case.
The HttpMessageNotReadableException does not expose methods to obtain the useful information separately. Furthermore, the exception message exists in different "flavors" and it does not use a common structure, thus string parsing seems infeasible.
Therefore, my question is: How to turn HttpMessageNotReadableException into human friendly message without exposing implementation details?