How to throw exception when there is extra parameters in request body spring boot

In my last project, there was a requirement for throwing exceptions when the request body contains extra parameters.

If the request will be like

    "name":"HR 1",

where test parameter is unnecessary and I've to return a response that should be like

    "timestamp": "2022-05-07T00:13:59.144657",
    "status": "500",
    "error": "Internal Server Error",
    "message": "test : must not be provided",
    "path": "/api/departments/HR"

I've shared the answer. How I handled it.

1 answer

  • answered 2022-05-06 19:22 abubakar butt

    In the I added this line.

    This helps us to make deserialization fail on unknown properties and throw an exception which we can handle using handleHttpMessageNotReadable

    create controller advice to handle exceptions

    public class CustomExceptionHandler extends ResponseEntityExceptionHandler {
        protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
            return new ResponseEntity("Your Response Object", HttpStatus.INTERNAL_SERVER_ERROR);

    That's the solution.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum