To create custom error, we need to know what kind of Exception error it is. The problem is I cannot determine what kind of error the "request body is missing one" is. At first I thought it was categorized as MethodArgumentNotValidException , but it doesn't catch the error.
I create the Controller Advice for the error
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException exception, HttpHeaders headers, HttpStatus status, WebRequest request){
MyObject<Object> error = MyObject.failure("Invalid Parameter");
log.error("argument invalid", exception);
return new ResponseEntity<Object>(error, new HttpHeaders(), HttpStatus.OK);
}
The controller
@PostMapping(value = "/tes")
public MyObject<MyRes> myTest(@Valid @RequestBody MyReq req, HttpServletRequest hsReq) throws Exception{
return myService.updateTestData(req);
}
I used Postman to call the API.
* First Trial with bracket

* Second Trial - without bracket

No error occurred.
My question is, how to handle this error, When no request body attached at all in the request. I want to return the "invalid param" error in this case too.
This might be late but you might want to try adding this on your ControllerAdvice class, that's how I caught the Required request body is missing error when trying to send an empty request.
@ExceptionHandler(HttpMessageNotReadableException.class)
public ResponseEntity<Object> handleMissingRequestBody(HttpMessageNotReadableException ex) {
return new ResponseEntity<Object>(ex.getMessage(), HttpStatus.BAD_REQUEST);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With