下面列出了javax.validation.ConstraintViolation#getMessageTemplate ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* ConstraintViolationException 参数错误异常
*/
@ExceptionHandler(ConstraintViolationException.class)
public Result handleConstraintViolationException(ConstraintViolationException e) throws Throwable {
errorDispose(e);
String smg = "";
Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
if (log.isDebugEnabled()) {
for (ConstraintViolation error : constraintViolations) {
log.error("{} -> {}", error.getPropertyPath(), error.getMessageTemplate());
smg = error.getMessageTemplate();
}
}
if (constraintViolations.isEmpty()) {
log.error("validExceptionHandler error fieldErrors is empty");
Result.ofFail(CommonErrorCode.BUSINESS_ERROR.getCode(), "");
}
return Result.ofFail(CommonErrorCode.PARAM_ERROR.getCode(), smg);
}
/**
* Extracts the error code for this particular constraint violation. If the {@link ConstraintViolation#getMessageTemplate()}
* seems to contain a customized error code, then we return that value as the error code. Otherwise, the default error
* code generator comes to play. For each constraint violation, we're going to generate a sensible default error code.
*
* @param violation The constraint violation representing a validation error.
* @return The custom or default error code.
*/
static String getErrorCode(ConstraintViolation<?> violation) {
String code = violation.getMessageTemplate();
boolean shouldGenerateDefaultErrorCode = code == null || code.trim().isEmpty() ||
DEFAULT_ERROR_CODES_PREFIX.stream().anyMatch(code::startsWith);
if (shouldGenerateDefaultErrorCode) {
String prefix = violation.getPropertyPath().toString();
Class<? extends Annotation> annotation = violation.getConstraintDescriptor().getAnnotation().annotationType();
String suffix = ERROR_CODE_MAPPING.getOrDefault(annotation, annotation.getSimpleName());
return prefix + "." + suffix;
}
return code.replace("{", "").replace("}", "");
}
private String toCode(ConstraintViolation<?> violation) {
if (violation.getConstraintDescriptor() != null) {
Annotation annotation = violation.getConstraintDescriptor().getAnnotation();
if (annotation != null) {
Class<?> clazz = annotation.getClass();
Class<?> superclass = annotation.getClass().getSuperclass();
Class<?>[] interfaces = annotation.getClass().getInterfaces();
if (superclass == Proxy.class && interfaces.length == 1) {
clazz = interfaces[0];
}
return clazz.getName();
}
}
if (violation.getMessageTemplate() != null) {
return violation.getMessageTemplate().replace("{", "").replaceAll("}", "");
}
return null;
}
@Override
public ErrorResponse toErrorResponse(ConstraintViolationException cve) {
LOGGER.warn("a ConstraintViolationException occured", cve);
List<ErrorData> errors = new ArrayList<>();
for (ConstraintViolation<?> violation : cve.getConstraintViolations()) {
ErrorDataBuilder builder = ErrorData.builder();
builder = builder.addMetaField(META_TYPE_KEY, META_TYPE_VALUE);
builder = builder.setStatus(String.valueOf(HttpStatus.UNPROCESSABLE_ENTITY_422));
builder = builder.setDetail(violation.getMessage());
builder = builder.setCode(toCode(violation));
if (violation.getMessageTemplate() != null) {
builder = builder.addMetaField(META_MESSAGE_TEMPLATE, violation.getMessageTemplate());
}
// for now we just provide root resource validation information
// depending on bulk update spec, we might also provide the leaf information in the future
if (violation.getRootBean() != null) {
ResourceRef resourceRef = resolvePath(violation);
builder = builder.addMetaField(META_RESOURCE_ID, resourceRef.getRootResourceId());
builder = builder.addMetaField(META_RESOURCE_TYPE, resourceRef.getRootResourceType());
builder = builder.setSourcePointer(resourceRef.getRootSourcePointer());
}
ErrorData error = builder.build();
errors.add(error);
}
return ErrorResponse.builder().setStatus(HttpStatus.UNPROCESSABLE_ENTITY_422).setErrorData(errors).build();
}
public ServiceMethodConstraintViolation(Class serviceInterface, ConstraintViolation violation) {
this.message = violation.getMessage();
this.messageTemplate = violation.getMessageTemplate();
this.invalidValue = violation.getInvalidValue();
this.constraintDescriptor = violation.getConstraintDescriptor();
this.executableParameters = violation.getExecutableParameters();
this.executableReturnValue = violation.getExecutableReturnValue();
this.rootBeanClass = serviceInterface;
this.propertyPath = violation.getPropertyPath();
}
/**
* Accepts the result from one of the many validation methods available and
* returns a List of ValidationErrors. If the size of the List is 0, no errors
* were encounter during validation.
*
* Usage:
* <pre>
* Validator validator = getValidator();
* List<ValidationError> errors = contOnValidationError(
* validator.validateProperty(myObject, "uuid"),
* validator.validateProperty(myObject, "name")
* );
* // If validation fails, this line will be reached.
* </pre>
*
* @param violationsArray a Set of one or more ConstraintViolations
* @return a List of zero or more ValidationErrors
* @since 1.0.0
*/
@SafeVarargs
protected final List<ValidationError> contOnValidationError(final Set<ConstraintViolation<Object>>... violationsArray) {
final List<ValidationError> errors = new ArrayList<>();
for (final Set<ConstraintViolation<Object>> violations : violationsArray) {
for (final ConstraintViolation violation : violations) {
if (violation.getPropertyPath().iterator().next().getName() != null) {
final String path = violation.getPropertyPath() != null ? violation.getPropertyPath().toString() : null;
final String message = violation.getMessage() != null ? StringUtils.removeStart(violation.getMessage(), path + ".") : null;
final String messageTemplate = violation.getMessageTemplate();
final String invalidValue = violation.getInvalidValue() != null ? violation.getInvalidValue().toString() : null;
final ValidationError error = new ValidationError(message, messageTemplate, path, invalidValue);
errors.add(error);
}
}
}
return errors;
}