For DTO validation, normally it will implement in different class property and trigger with @Validate annotation. However, it will not be trigger when method call due to performance issue.
We can trigger the checking in code. And it is recommend for API response after collect API response.
Code to validate response in code level, it can be move to abstract class or interface and call it when needed.
import javax.validation.ConstraintViolation; ApiResponse response = ApiClient.get(); Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); Set<ConstraintViolation<ApiResponse>> result = validator.validate(response); if(!result.isEmpty()) { String message = result.stream() .map(o-> new StringBuilder() .append(o.getPropertyPath().toString()) .append(o.getMessage())) .collect(Collectors.joining(";\r\n")); throw new IllegalArgumentException(message); }
Leave a Reply