Spring Boot how to return my own validation constraint error messages

If this can help, I found the solution for this issue here: https://howtodoinjava.com/spring-boot2/spring-rest-request-validation/

You have to add this method to your CustomResponseEntityExceptionHandler class:

 @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        List<String> details = new ArrayList<>();
        for(ObjectError error : ex.getBindingResult().getAllErrors()) {
            details.add(error.getDefaultMessage());
        }
        ErrorMessage error = new ErrorMessage(new Date(), details.toString());
        return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
    }

Yes it is doable & spring very well supports it. You are just missing some configuration to enable it in spring.

  • Use Spring@Validated annotation to enable spring to validate controller
  • Handle ConstraintViolationException in your ControllerAdvice to catch all failed validation messages.
  • Mark required=false in @RequestParam, so it will not throw MissingServletRequestParameterException and rather move to next step of constraint validation.
@ControllerAdvice
public class CustomResponseEntityExceptionHandler {

    @ExceptionHandler
  public ResponseEntity<ApiError> handle(ConstraintViolationException exception) {
        //you will get all javax failed validation, can be more than one
        //so you can return the set of error messages or just the first message
        String errorMessage = new ArrayList<>(exception.getConstraintViolations()).get(0).getMessage();
       ApiError apiError = new ApiError(errorMessage, errorMessage, 1000);    
       return new ResponseEntity<ApiError>(apiError, null, HttpStatus.BAD_REQUEST);
  }
}



@RestController
@Validated
public class MinimumStockController {

    @RequestMapping(value = "/minimumstock")
    public Product product(
            @RequestParam(value = "product.sku", required=false) @NotEmpty(message = "Product.sku cannot be empty") String sku,
            @RequestParam(value = "stock.branch.id", required=false) String branchID) {
        return null;
    }
}

NOTE: MissingServletRequestParameterException won't have access to javax validation messages, as it is thrown before constraint validation occurs in the request lifecycle.