JSR 303 ConstraintViolationException and detailed message
Asked Answered
I

1

6

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 ?

Ivett answered 4/2, 2017 at 14:2 Comment(0)
R
8

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"

Rundlet answered 4/2, 2017 at 15:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.