Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create custom "Request Body is Missing" error in Spring Boot

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

with bracket

* Second Trial - without bracket

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.

like image 833
chronos14 Avatar asked Jul 11 '26 05:07

chronos14


1 Answers

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);
}
like image 82
jcaronan Avatar answered Jul 13 '26 17:07

jcaronan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!