1 引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
2 Controller 中使用
@PostMapping("/testval")
public Object testVal(@Validated @RequestBody TGiftPO po){
// var r = extSchoolMService.sync();
return Result.success(po);
}
3 PO 中进行标记
@Data
public class TGiftPO {
@NotNull(message = "title 不可为空")
String title;
String img;
Integer score;
}
全局异常类中进行捕捉
import com.adea.tool.result.Result;
import com.adea.tool.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
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 org.springframework.web.bind.annotation.ResponseStatus;
import java.util.List;
@Slf4j
@ControllerAdvice
public class ValidatedExceptionHandler {
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public Result exceptionHandler(MethodArgumentNotValidException exception){
BindingResult result = exception.getBindingResult();
StringBuilder stringBuilder = new StringBuilder();
if (result.hasErrors()){
List<ObjectError> errors = result.getAllErrors();
if (errors != null){
errors.forEach(p ->{
FieldError fieldError = (FieldError) p;
stringBuilder.append(fieldError.getDefaultMessage());
});
}
}
return Result.error(ResultCode.USER_PARAM_ERROR,stringBuilder.toString());
}
}
axios 的配置
if(error.response.data && error.response.data.message){
ElMessage({
message: error.response.data.message,
type: 'error',
duration: 3 * 1000
})
}
相关注解

image.png