abubakar butt
abubakar butt

Reputation: 131

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

{
   "test":"body",
    "name":"HR 1",
    "location":"Location"
}

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.

Upvotes: 3

Views: 1464

Answers (1)

abubakar butt
abubakar butt

Reputation: 131

In the application.properties I added this line.

spring.jackson.deserialization.fail-on-unknown-properties=true

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

@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {
    @Override
    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.

Upvotes: 5

Related Questions