在spring里面有一个注解 @Validated
可以在方法的入参里面这样写
//方法
getActivityFlag(@RequestBody @Validated QueryActivityDto queryActivityDto)
//参数详情
@NotBlank(message = "userId不能为空")
private String userId;
@NotNull(message = "storeId不能为空")
private String storeId;
@NotBlank(message = "festivalId不能为空")
private String festivalId;
然后进行报错拦截即可,拦截方式有多种
1、直接在切面进行拦截
实现如下方法
private static Validator validator = Validation.byProvider(HibernateValidator.class).configure().failFast(true) .buildValidatorFactory().getValidator(); /** * @param object object * @param groups groups */ public static void validateObject(Object object, Class<?>... groups) throws ValidationException { Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups); if (constraintViolations.stream().findFirst().isPresent()) { throw new ValidationException(constraintViolations.stream().findFirst().get().getMessage()); } }
2、进行自定义异常处理
ExceptionHandler(VvipException.class) public ResultMsg handleException(VvipException e) { // 打印错误信息 StackTraceElement s = e.getStackTrace()[0]; log.error("msg:【{}】,file:【{}】,line:【{}】,method:【{}】", e.getMessage(), s.getFileName(), s.getLineNumber(), s.getMethodName()); return ResultMsg.error(e.getErrorCode().getValue(), e.getMessage()); } private static String getParamErrorMsg(BindingResult bind) { String[] str = Objects.requireNonNull(bind.getAllErrors().get(0).getCodes())[1].split("\\."); String message = bind.getAllErrors().get(0).getDefaultMessage(); String msg1 = "不能为空"; String msg2 = "不能为null"; String msg3 = "must not be null"; String msg4 = "must not be empty"; if (msg1.equals(message) || msg2.equals(message) || msg3.equals(message) || msg4.equals(message) ) { message = ArrayUtil.join(ArrayUtil.remove(str, 0), ".") + ":" + message; } return message; }
3、还有一种就是在参数后面加一个 BindingResult对象(不推荐 耦合度太高)
findMemberByUnionid(@RequestBody @Validated QueryMemberByUnionidDto queryMemberDto, BindingResult result) { if(result.hasErrors()){ result.getFieldErrors().forEach((item)->{ log.error("参数错误:{}",item.getDefaultMessage()); }); }