package thyyxxk.webserver.utils;


import thyyxxk.webserver.config.exception.BizException;
import thyyxxk.webserver.config.exception.ExceptionEnum;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import java.util.Set;

public class ValidatorUtils {
    private static final ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();

    public static void validate(Object object) {
        Set<ConstraintViolation<Object>> violations = validatorFactory.getValidator().validate(object);

        int index = 1;

        if (!violations.isEmpty()) {
            StringBuilder errorMsg = new StringBuilder();
            for (ConstraintViolation<Object> violation : violations) {
                errorMsg.append("\n").append(index).append("、").append(violation.getMessage());
                index++;
            }
            throw new BizException(ExceptionEnum.LOGICAL_ERROR, errorMsg.toString());
        }
    }
}
