Skip to content
Advertisement

How to handle “org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error” in Spring?

I’m adding an API to an existing Spring Boot project using @RestController.

My Spring Boot experience is: This is my first time using it.

The RestController works fine when I make a properly formed request but throws an error if the request is not correct (this is what I would expect). However, I can’t figure out how to give a meaningful error response to a user.

This is the Controller class:

JavaScript

This is the Config class:

JavaScript

If I run the application and hit localhost:8080/update with:

JavaScript

Then everything is all good and we can //do stuff.

However if I hit localhost:8080/update with:

JavaScript

I get an exception: .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type...

This is expected since I provided a number and a String was needed for thing2.

The response I get is: <h1>sorry</h1>

I’m not sure if this is a Spring default or configured somewhere in the application (if it is I cannot find it).

I want to change that to something meaningful like: “You gave an incorrect value for thing2”.

But since the code never reaches //do stuff I’m not sure how to handle this?

I tried to make an exception class with:

JavaScript

But I get a “Cannot resolve symbol HttpMessageNotReadableException” from the IDE. I’m not even sure if making an exception class is the right way to handle it though?

Edit: In this tutorial (https://www.toptal.com/java/spring-boot-rest-api-error-handling) the Spring default message is something like:

JavaScript

But I just get <h1>sorry</h1>. I actually want something more like the above.

Advertisement

Answer

This should work but Spring is not meant to handle error before the HTTP request can be deserialized correctly. You can write rules on request data after deserialization using annotation on your DTO class’s fields like @NotNull, @NotEmpty, @Positive, …

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement