1. Springboor2.3.0以后的字段校验注解没有集成在springboot上,需要手动引入依赖才会生效
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<version>3.0.2</version>
</dependency>
2. 进行特定异常捕获
@ExceptionHandler(MethodArgumentNotValidException.class)
public R MethodArgumentNotValidException(MethodArgumentNotValidException e){
Map<String,String> map=new HashMap<>();
List<FieldError> fieldErrors = e.getFieldErrors();
fieldErrors.forEach((fieldError) -> {
String field = fieldError.getField();
String defaultMessage = fieldError.getDefaultMessage();
map.put(field,defaultMessage);
});
return R.error(400,"数据校验异常").put("data",map);
}