分组校验
public void validData(Object bean,Class<?>... groups) { String errMessage = validate(bean,groups); if (errMessage .length>0) { throw new BusinessException(SystemErrcode.xxx.getCode,errMessage);
}
} private static String validate(Object obj,Class<?>... groups) { //存储验证后的错误信息 StringBuffer sb = new StringBuffer(); Validator validator=getValidator(); //验证某个对象的所有属性 Set<ConstraintViolation<Object>> constrainViolation= validator.validate(obj,groups); Iter<ConstraintViolation<Object>> iter =constrainViolation.iterator(); while(iter.hasNext()) { String message=iter.next().getMessage(); sb.append(message); break; } return sb.toString(); } private static Validator getValidator() { return Validation.buildDefaultValidatorFactory().getValidator() }
@NotNull 通用
@NotBlank String类型
@NotEmpty 非String类型,如List类型
注意,如果是Integer、Long类型的话,只能用@NotNull
通用异常:
public abstract class BasicException extends Exception { private String code; private String message;
public BE(String code) {
super();
this.code=code;
}
public BE(String code,String message) {
super(message);
this.code=code;
this.message=message;
}
public BE(String code,String message,Throwable cause) {
super(message,cause);
this.code=code;
this.message=message;
}
然后get、set方法, 有参方法及有参的3个参数,包括Throwable cause 方法里面是信息都是super(参数) this.参数=参数 }
项目具体异常的话直接继承上面的通用异常即可。
如
Public class BusinessException extends BasicException { Public BusinessException (String code) { super(code); } Public BusinessException (String code,String message) { super(code,message); } Public BusinessException (String code,String message,Throwable cause) { super(code,message,cause); } }
@ExceptionHandler({Exception.class}) public xxx defaultErrorHandler(HttpServletRequest request,Exception e) { String errMsg="未知错误"; String code="500"; log.error("类名 requestPath:{} errorMessage:{} error:{}",request.getRequestURI,e.toString(),e); if (e instanceof XXXException) { errMsg="XX错误"; code="xxxxx"; } else if(e instanceof BusinessException) { errMsg=e.getMessage(); code=((BusinessException)e).getCode(); }else { String message=e.getMessage(); if (e instanceof BusinessException) { errMsg=message; String errCode=((BusinessException) e).getCode(); } } }