Springboot 版本 2.2.2.RELEASE
实体校验成功,但是方法校验失败
生效条件
- 方法必须是
public
- 方法的类名上要有注解
@Validated
两个条件达成即可生效校验注解
需要注意的是:校验失败会抛出异常ConstraintViolationException
示例代码:
@RestController
@Slf4j
@RequiresRoles(Constant.ROLE_KEY.ADMIN)
@RequestMapping("api/v1/sys/plan")
//标记类名
@Validated
public class PlanController extends BaseController {
@GetMapping("/{planKey}/enable")
@Transactional
public JsonResult<PlanEntity> setPlanEnable(
@PathVariable String planKey,
@EnumValid(value = Constant.STATUS.class,message = "枚举不正确") Integer enableStatus){
return succeed(planService.setPlanEnable(planKey,enableStatus));
}
}
声明:@EnumValid
是自定义注解
捕获异常:
@ControllerAdvice
@ResponseBody
@Slf4j
public class MyExceptionHandler {
@ExceptionHandler(ConstraintViolationException.class)
public JsonResult<List<String>> ConstraintViolationException(ConstraintViolationException e){
List<String> list= CollectionUtil.newArrayList();
for (ConstraintViolation<?> v:e.getConstraintViolations()){
list.add(v.getMessage());
}
return JsonResult.error(Constant.ERROR_CODE.VALIDATOR_EXCEPTION,list);
}
}