Issue
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.
Solution
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.
Answered By - abubakar butt
Answer Checked By - Terry (JavaFixing Volunteer)