当前位置: 代码迷 >> 综合 >> SpringBoot使用Validation校验参数后 并没有抛出BindException异常 直接抛出了Exception 导致无法捕捉
  详细解决方案

SpringBoot使用Validation校验参数后 并没有抛出BindException异常 直接抛出了Exception 导致无法捕捉

热度:16   发布时间:2024-02-24 17:25:36.0

背景:

SpringBoot使用Validation校验参数后 并没有抛出BindException异常 直接抛出了Exception 导致无法捕捉

报错如下

[ERROR] com.adc.product.biz.exception.WorldBaseExceptionAdvice:61 - Validation failed for argument [0] in public com.adc.da.util.http.ResponseMessage<com.adc.product.db.entity.Product> com.adc.product.biz.controller.ProductController.update(com.adc.product.db.vo.ProductVO) throws java.lang.Exception with 3 errors: [Field error in object 'productVO' on field 'servName': rejected value []; codes [Length.productVO.servName,Length.servName,Length.java.lang.String,Length]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [productVO.servName,servName]; arguments []; default message [servName],120,1]; default message [服务商名称长度不能大于120字符]] [Field error in object 'productVO' on field 'email': rejected value [1234689]; codes [Email.productVO.email,Email.email,Email.java.lang.String,Email]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [productVO.email,email]; arguments []; default message [email],[Ljavax.validation.constraints.Pattern$Flag;@44314aab,.*]; default message [服务商邮箱格式不正确]] [Field error in object 'productVO' on field 'servName': rejected value []; codes [NotEmpty.productVO.servName,NotEmpty.servName,NotEmpty.java.lang.String,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [productVO.servName,servName]; arguments []; default message [servName]]; default message [服务商名称不能为空]] 

 解析:

查看报错,发现报出了MethodArgumentNotValidException

解决方法:

在ExceptionHandle类中添加此Exception捕获即可

	/*** 校验错误拦截处理** @param exception 错误信息集合* @return 错误信息*/@ExceptionHandler(MethodArgumentNotValidException.class)@ResponseBodypublic ResponseMessage validationBodyException(MethodArgumentNotValidException exception) {List<ObjectError> allErrors = exception.getBindingResult().getAllErrors();List<String> errors = new ArrayList<>();for (ObjectError allError : allErrors) {errors.add(allError.getDefaultMessage());}return Result.error("500",errors.toString());}

 

  相关解决方案