简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM