package com.zy.platform.common.core.utils;
import org.apache.commons.lang3.StringUtils;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.Set;
import java.util.StringJoiner;
public class ValidatorUtil {
public static void doValidate(Object o) {
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set> constraintViolations = validator.validate(o, Default.class);
if (!constraintViolations.isEmpty()) {
StringBuilder msg = new StringBuilder();
for (ConstraintViolation
GlobalExceptionHandler:
package com.zy.platform.common.core.exception;
import com.zy.platform.common.core.web.ServerResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
/**
* @author javachen
* @description 全局异常处理类
*/
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler{
@ResponseBody
@ExceptionHandler(CustomException.class)
public ServerResponse customException(CustomException e){
log.error("全局异常信息 ex={}", e.getMessage(), e);
if(null!=e.getCode()){
return ServerResponse.createByErrorCodeMessage(e.getCode(),e.getMessage());
}else{
return ServerResponse.createByErrorMessage(e.getMessage());
}
}
@ResponseBody
@ExceptionHandler(Exception.class)//指定出现什么异常执行这个方法
public ServerResponse error(Exception e){
log.error("自定义异常信息 ex={}", e.getMessage(), e);
return ServerResponse.createByErrorMessage(e.getMessage());
}
@ResponseBody
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public ServerResponse MyExceptionHandle(MethodArgumentNotValidException exception){
exception.printStackTrace();
BindingResult result = exception.getBindingResult();
StringBuilder errorMsg = new StringBuilder() ;
if (result.hasErrors()) {
List fieldErrors = result.getFieldErrors();
exception.printStackTrace();
return ServerResponse.createByErrorMessage(fieldErrors.get(0).getDefaultMessage().toString());
}
return ServerResponse.createBySuccess();
}
}
test:
//进行参数校验
ValidatorUtil.doValidate(sysUserAddBO,Insert.class);
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)