springboot 实体参数校验 validate 抛出javax.validation.ConstraintViolationException异常 统一处理
2021-04-24 07:28
标签:spring def 处理 col fas hibernate bean 图片 constrain springboot 实体参数校验 validate 抛出javax.validation.ConstraintViolationException异常 统一处理 标签:spring def 处理 col fas hibernate bean 图片 constrain 原文地址:https://www.cnblogs.com/austinspark-jessylu/p/13265334.html
@ControllerAdvice
public class WebExceptionHandler {
//处理Get请求中 使用@Valid 验证路径中请求实体校验失败后抛出的异常,详情继续往下看代码
@ExceptionHandler(BindException.class)
@ResponseBody
public Result BindExceptionHandler(BindException e) {
String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
return Result.build(ResultCode.PARAM_ERROR.getCode(),message);
}
//处理请求参数格式错误 @RequestParam上validate失败后抛出的异常是javax.validation.ConstraintViolationException
@ExceptionHandler(ConstraintViolationException.class)
@ResponseBody
public Result ConstraintViolationExceptionHandler(ConstraintViolationException e) {
String message = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining());
return Result.build(ResultCode.PARAM_ERROR.getCode(),message);
}
//处理请求参数格式错误 @RequestBody上validate失败后抛出的异常是MethodArgumentNotValidException异常。
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
public Result MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
return Result.build(ResultCode.PARAM_ERROR.getCode(),message);
}
}@Configuration
public class WebParamValidateConfig {
@Bean
public Validator validator() {
ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
.configure()
//failFast的意思只要出现校验失败的情况,就立即结束校验,不再进行后续的校验。
.failFast(true)
.buildValidatorFactory();
return validatorFactory.getValidator();
}
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
MethodValidationPostProcessor methodValidationPostProcessor = new MethodValidationPostProcessor();
methodValidationPostProcessor.setValidator(validator());
return methodValidationPostProcessor;
}
}
文章标题:springboot 实体参数校验 validate 抛出javax.validation.ConstraintViolationException异常 统一处理
文章链接:http://soscw.com/index.php/essay/78843.html