In this post, we will explore what is HttpMessageNotReadableException
, how to reproduce it, and what are the
possible solutions.
The HttpMessageNotReadableException
is thrown when the request payload (body) is not readable. This can
happen
for various reasons:
Create a Student
class with the following content:
class Student {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Next, let's create a StudentController
with the following REST API:
@RestController
@RequestMapping("/api/students")
public class StudentController {
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Student> student(@RequestBody Student student) {
return ResponseEntity.ok(student);
}
}
Next, call the above REST API using Postman and make sure to pass malformed JSON in the request body:
{
"firstName": "John",
"lastName": 123 // Invalid type
}
You will encounter the HttpMessageNotReadableException
:
Ensure the client sends data in the correct format. This can be clarified with proper API documentation.
Use Spring's @ExceptionHandler to catch the exception and return a more user-friendly message:
@ExceptionHandler(HttpMessageNotReadableException.class)
public ResponseEntity<String> handleInvalidInput(HttpMessageNotReadableException e) {
return ResponseEntity.badRequest().body("Invalid request payload.");
}
Use Java's built-in validation API along with annotations like @Valid
to enforce structured
data.
Where possible, provide descriptive error messages. For instance, instead of saying "Invalid Input", you might specify that a certain field was missing or was of the wrong type.
HttpMessageNotReadableException gives a clear indication that the client has sent data in an unexpected format, and with the right handling, can make the API more robust and user-friendly.