How to turn HttpMessageNotReadableException into human friendly message without exposing implementation details?

Viewed 431

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?

1 Answers

You can dig out the underlying JsonParseException that you see in your stack trace via the method Throwable.getCause that HttpMessageNotReadableException inherits from Throwable. It might require recursive application depending on how deep it's buried in your stack trace. JsonParseException has several getters that can return some of the info you want.

However, I'd not bother with reformatting this error message. It will simplify debugging if you leave it as is.

Related