HttpMessageNotReadableException in Spring Boot

In this post, we will explore what is HttpMessageNotReadableException, how to reproduce it, and what are the possible solutions.

What is HttpMessageNotReadableException? 

The HttpMessageNotReadableException is thrown when the request payload (body) is not readable. This can happen for various reasons: 

  • The JSON sent by the client might be malformed. 
  • There might be a type mismatch, such as sending a string where an integer is expected. 
  • Missing essential properties that are marked as required in the DTO (Data Transfer Object).

Reproduce Step-By-Step

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, let's call the above REST API using Postman and make sure to pass malformed JSON in the request body:

You will encounter the HttpMessageNotReadableException:

Solutions

Proper Client Data

Ensure the client sends data in the correct format. This can be clarified with the proper API documentation. 

Handle the Exception Gracefully

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.");
}

Utilize Validation

Use Java's built-in validation API along with annotations like @Valid to enforce structured data. 

Descriptive Error Messages

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. 

Conclusion

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.

Related Spring Exceptions Posts

Comments