BackendBench
Coffee

Home โ€บ Java exceptions โ€บ HttpMessageNotReadableException

Unchecked exception ยท org.springframework.http.converter

HttpMessageNotReadableException: causes and fixes

Spring MVC could not read the request body: invalid JSON, missing body or a type mismatch.

What it looks like

org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.lang.Integer` from String "abc"

Extends HttpMessageConversionException in org.springframework.http.converter.

What it means

Spring MVC converts the request body to your @RequestBody parameter with an HttpMessageConverter, usually Jackson. If the body cannot be read, the converter fails and Spring raises this exception, which the default handler turns into a 400 Bad Request. The message includes Jackson's explanation (and the line and column in the body), or says "Required request body is missing" when no body was sent at all.

Common causes

How to fix it

  1. Reproduce with curl and check the JSON with a validator; read the line and column in the message.
  2. Send Content-Type: application/json and the right date format (ISO 8601 by default).
  3. Handle the exception in a @ControllerAdvice and return a readable error body.
  4. Make the request class deserialisable: default constructor, @JsonCreator, or a record.

Broken and fixed

fails
curl -X POST /orders -d "{name: bob,}" # invalid JSON
works
curl -X POST /orders -H "Content-Type: application/json" -d '{"name":"bob"}'

๐Ÿ”Ž Unravel the failing code ๐Ÿ”Ž Unravel the fix

In Spring and enterprise code

Spring Boot sets FAIL_ON_UNKNOWN_PROPERTIES to false by default, so extra fields are ignored unless you changed it.

Debug it faster

Paste the whole stack trace into the stack trace beautifier to hide framework frames, jump to the root cause and find the first line of your own code. It runs in your browser, so the trace never leaves your machine.

Frequently asked questions

Is HttpMessageNotReadableException a checked or unchecked exception?

HttpMessageNotReadableException is an unchecked exception (it extends HttpMessageConversionException, which is a RuntimeException), so you are not forced to catch it. Prevent it with validation, or handle it where the input enters the system.

Which package is HttpMessageNotReadableException in?

It lives in org.springframework.http.converter, so the import is import org.springframework.http.converter.HttpMessageNotReadableException;.

What is the first thing to check when I see HttpMessageNotReadableException?

Read the message and the first stack trace line in your own code. The usual causes are: Malformed JSON: a trailing comma, single quotes, an unescaped character; and A value of the wrong type for a field, such as text for a number or a bad date format.

Related exceptions

More tools you might need