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

M. Deinum
  • 115,695
  • 22
  • 220
  • 224
alok
  • 2,718
  • 21
  • 17
  • please check here: [Spring @Validated in service layer](https://stackoverflow.com/questions/19425221/spring-validated-in-service-layer#19426570) – sudipn Dec 17 '19 at 08:46
  • also, DZone [Method Validation With Spring 3.1 and Hibernate Validator 4.2](https://dzone.com/articles/method-validation-spring-31) – sudipn Dec 17 '19 at 08:55

1 Answers1

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;
}

}

alok
  • 2,718
  • 21
  • 17