0

I am using custom validation in entity class, @Valid annotation on service class not in controller class and custom exception controller(@ControllerAdvice) in Spring Boot.

When I am using @Valid in controller the custom annotation is throwing MethodArgumentNotValidException and I am able to handle it.

The problem comes when I am using @Valid in service class the custom annotation stopped thowing exception. I want to handle custom annotation in ConstraintViolationException. I am using custom annotation on object level not field level. Please help

2

1 Answer 1

0

I got the solution is is look like following:

@ExceptionHandler(ConstraintViolationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
ValidationErrorReponse onConstraintValidationException(ConstraintViolationException e) {
    ValidationErrorReponse error = new ValidationErrorReponse();
    Map<String, List<String>> errorMap = new HashMap<>();
    List<Violation> violations = new ArrayList<>();
    for (ConstraintViolation<?> violation : e.getConstraintViolations()) {
        if (!errorMap.containsKey(violation.getPropertyPath().toString())) {
              List<String> errorMessages = new ArrayList<>();
            if(!violation.getMessage().isEmpty()) {
                errorMessages.add(violation.getMessage());
                errorMap.put(violation.getPropertyPath().toString(), errorMessages);                    
            }else {
                ConstraintDescriptor<?> objEceptions = violation.getConstraintDescriptor();
                errorMessages.add((String)objEceptions.getAttributes().get("errormessage"));
                String errorField = (String)objEceptions.getAttributes().get("errorField");
                errorMap.put(violation.getPropertyPath().toString().concat("."+errorField), errorMessages);  
            }
        } else {
            errorMap.get(violation.getPropertyPath().toString()).add(violation.getMessage());
        }
    }
    for (Entry<String, List<String>> entry : errorMap.entrySet()) {
        Violation violation = new Violation(entry.getKey(), entry.getValue());
        violations.add(violation);
    }
    error.setViolations(violations);
    return error;
}

}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.