javaspringvalidationbean-validationjsr

JSR 303 ConstraintViolationException and detailed message


I have configured my Spring Boot 1.5.1 application with JSR 303 validation. Right now I'm getting ConstraintViolationException in case of wrong data.

Is it possible to get a detailed message(now it is null) about what was wrong(for example what field or method parameter violates constraints) with ConstraintViolationException ?


Solution

  • Well, your ConstraintViolationException has a set of ConstraintViolation objects. Each of them has the details that you want.

    public static <T> String getValidationMessage(ConstraintViolation<T> violation) {
        String className = violation.getRootBeanClass().getSimpleName();
        String property = violation.getPropertyPath().toString();
        //Object invalidValue = violation.getInvalidValue();
        String message = violation.getMessage();
        return String.format("%s.%s %s", className, property, message);
    }
    

    With this I would get a message like, e.g "OrderLine.quantity must be greater than 0"