在RESTful中使用Hibernate-Validator的時候,都是這樣一種方法使用。或者類似的方式進行異常校驗。我也是參照了別人的文檔這麼寫的。
/**
* 接口入參數據校驗工具類.
* 使用hibernate-validator進行校驗.
* 其中加入自定義的校驗器
*
* @author wuss45
* @date 2018年10月19日-17時08分
*/
public class ValidationUtil {
private static final Logger logger = LoggerFactory.getLogger(ValidationUtil.class);
/**
* 使用hibernate的註解來進行驗證
*/
private static Validator validator = Validation
.byProvider(HibernateValidator.class).configure().failFast(true).buildValidatorFactory().getValidator();
/**
* 默認校驗器校驗
*
* @param obj
*/
public static <T> Result defaultValidate(T obj) {
logger.info("開始對類型{}進行校驗", obj.getClass());
try {
Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj);
if (constraintViolations.size() > 0) {
String message = constraintViolations.iterator().next().getMessage();
logger.warn("存在不在異常枚舉中的異常:{}", message);
return ResponseUtil.operateFail(999999, message);
}
logger.info("表單校驗通過");
return null;
} catch (Exception ex) {
Throwable cause = ex.getCause();
//判斷異常類型,業務異常包裝一下再返回
if (cause instanceof SpecialException) {
ExceptionEnum exceptionEnum = ((SpecialException) cause).getExceptionEnum();
logger.warn("對錶單類{}校驗存在異常:{}", obj.getClass(), exceptionEnum.getMessage());
return ResponseUtil.operateFail(exceptionEnum.getCode(), exceptionEnum.getMessage());
}
logger.error("系統錯誤");
return null;
}
}
}
但是這樣寫你會發現,Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj);中的constraintViolations只是包含一個錯誤信息。
究其原因,上面的代碼是構建校驗器的時候傳遞的參數配置決定的。我們來看:private static Validator validator = Validation
.byProvider(HibernateValidator.class).configure().failFast(true).buildValidatorFactory().getValidator();
代碼" .failFast(true) " ,當參數爲true的時候,遇到一次個錯誤信息就會返回。我要獲取全部的錯誤信息,需要把這個true改爲false。
我們來看一下這個方法的源碼註釋:
/**
* En- or disables the fail fast mode. When fail fast is enabled the validation
* will stop on the first constraint violation detected.
*
* @param failFast {@code true} to enable fail fast, {@code false} otherwise.
*
* @return {@code this} following the chaining method pattern
*/
HibernateValidatorConfiguration failFast(boolean failFast);