All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.iiifi.kite.boot.common.error.BaseExceptionTranslator Maven / Gradle / Ivy

There is a newer version: 1.2.4.RELEASE
Show newest version
package com.iiifi.kite.boot.common.error;

import java.util.Set;
import com.iiifi.kite.common.result.Result;
import javax.validation.ConstraintViolation;
import com.iiifi.kite.common.result.SystemCode;
import org.springframework.validation.FieldError;
import org.springframework.validation.BindingResult;
import org.hibernate.validator.internal.engine.path.PathImpl;

/**
 * 抽取共性 通用部分代码
 * @author [email protected] 花朝
 * @date 2018/8/18 12:59
 */
public abstract class BaseExceptionTranslator {

	/**
	 * 处理 BindingResult
	 * @param result BindingResult
	 * @return Result
	 */
	protected Result handleError(BindingResult result) {
		FieldError error = result.getFieldError();
		String message = String.format("%s:%s", error.getField(), error.getDefaultMessage());
		return Result.fail(SystemCode.PARAM_BIND_ERROR, message);
	}

	/**
	 * 处理 ConstraintViolation
	 * @param violations 校验结果
	 * @return Result
	 */
	protected Result handleError(Set> violations) {
		ConstraintViolation violation = violations.iterator().next();
		String path = ((PathImpl) violation.getPropertyPath()).getLeafNode().getName();
		String message = String.format("%s:%s", path, violation.getMessage());
		return Result.fail(SystemCode.PARAM_VALID_ERROR, message);
	}
}