【问题标题】:How to handle custom annotation while adding @valid in service class在服务类中添加@valid时如何处理自定义注释
【发布时间】:2020-04-09 14:58:29
【问题描述】:
我在实体类中使用自定义验证,服务类上的@Valid 注释不在控制器类中,并且在 Spring Boot 中使用自定义异常控制器(@ControllerAdvice)。
当我在控制器中使用@Valid 时,自定义注释会抛出MethodArgumentNotValidException,我能够处理它。
问题来了
当我在服务类中使用@Valid 时,自定义注释停止抛出异常。我想处理ConstraintViolationException 中的自定义注释。我在对象级别而不是字段级别上使用自定义注释。请帮忙
【问题讨论】:
标签:
java
spring-boot
constraints
exceptionhandler
constraintviolationexception
【解决方案1】:
我得到的解决方案如下所示:
@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;
}
}