Home > OS >  Java/Spring: Override default @RequestBody functionality
Java/Spring: Override default @RequestBody functionality

Time:10-03

So I have this API:

public Map<String, Object> myFunc(@RequestBody @Valid MyPrivateEntity body) {}

Which is marked with @RequestBody and @Valid

The thing is, if I omit the body when calling this API, I get the following error message:

{
"title": "Failed to parse request",
"detail": "Required request body is missing: public com.privatePackage.misc.service.rest.MyPrivateEntity com.privatePackage.misc.service.rest.MyPrivateResource.myFunc(java.lang.String, com.privatePackage.misc.service.rest.MyPrivateEntity)",
"status": 400

}

I don't want the error message to include class names and paths, instead just "Required request body is missing".

How can I do that?

Thanks

CodePudding user response:

Try @ControllerAdvice to customise your message.

@ControllerAdvice
        public class RestExceptionHandler extends ResponseEntityExceptionHandler {
    
            @Override
            protected ResponseEntity<Object> handleHttpMessageNotReadable(
                HttpMessageNotReadableException ex, HttpHeaders headers,
                HttpStatus status, WebRequest request) {
                // paste custom hadling here
            }
        }

Reference:

https://ittutorialpoint.com/spring-rest-handling-empty-request-body-400-bad-request/

CodePudding user response:

Try this code

@ExceptionHandler(BindException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)  // return 400 if validate fail
public String handleBindException(BindException e) {
    // return message of first error
    String errorMessage = "Request not found";
    if (e.getBindingResult().hasErrors())
        e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
    return errorMessage;
}

Or use this way

public Map<String, Object> myFunc(
        @RequestBody @Valid MyPrivateEntity body,
        BindingResult bindingResult) {  // add this parameter
    // When there is a BindingResult, the error is temporarily ignored for manual handling
    // If there is an error, block it
    if (bindingResult.hasErrors())
        throw new Exception("...");

}

Reference: https://www.baeldung.com/spring-boot-bean-validation

  • Related