springboot validation 统一返回错误信息

首先引入springboot包


        compile group: 'org.springframework.boot', name: 'spring-boot-starter-validation'

然后创建一个实体类

@Setter
@Getter
public class CountryBo {
    @NotNull(message = "{region.error.null}")
    @Length(max = 10,message = "{region.error.length}")
    private String region;
    @NotNull(message = "{countryCode.error.null}")
    @Length(max = 10,message = "{countryCode.error.length}")
    private String countryCode;
}
  • 这里使用了消息文件直接把ValidationMessages.properties文件放到resource目录下,也可通过springboot的配置自定义文件名
region.error.null=region is not allow null
region.error.length=More than the length of region
countryCode.error.null=region is not allow null
countryCode.error.length=More than the length of region
id.error.null=id is not allow null
id.error.length=More than the length of id

创建Controller类

@RestController
@Api(tags = "测试类")
@Slf4j
public class TestController {
    @Autowired
    private TestService testService;
    @GetMapping("/testsql")
    @ApiOperation("测试SqlServer")
    public JsonResult test(@Valid CountryBo contry){
        JsonResult jsonResult = new JsonResult();
        try{
            jsonResult.setData(testService.test(contry));
            return jsonResult;
        }catch (NecServiceExcepiton e){
            log.error("excute failed :{}",e.getMessage());
            jsonResult.setCode(e.getErrorCode());
            jsonResult.setMsg("处理失败");
            return jsonResult;
        }catch (Exception e){
            log.error("excute failed :{}",e.getMessage());
            jsonResult.setCode("90001");
            jsonResult.setMsg("处理异常");
            return jsonResult;
        }
    }

    @GetMapping("/testMongo")
    @ApiOperation("测试Mongo")
    @ApiParam()
    public JsonResult testMongo(@Valid PartsBo partsBo){
        JsonResult jsonResult = new JsonResult();
        try{
            jsonResult.setData(testService.testMongo(partsBo));
            return jsonResult;
        }catch (NecServiceExcepiton e){
            log.error("excute failed :{}",e.getMessage());
            jsonResult.setCode(e.getErrorCode());
            jsonResult.setMsg("处理失败");
            return jsonResult;
        }catch (Exception e){
            log.error("excute failed :{}",e.getMessage());
            jsonResult.setCode("90001");
            jsonResult.setMsg("处理异常");
            return jsonResult;
        }
    }

}

重写ResponseEntityExceptionHandler类的handleBindException(重点)

@ControllerAdvice
public class ValidatorHandlerAdvice extends ResponseEntityExceptionHandler {
    @Override
    protected ResponseEntity<Object> handleBindException(
            BindException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        String message = "";
        JsonResult jsonResult = new JsonResult();
        for(ObjectError error:ex.getBindingResult().getAllErrors()){
            jsonResult.setCode("V0001");
            jsonResult.setMsg(error.getDefaultMessage());
        }
        return new ResponseEntity<Object>(jsonResult, status);
    }
}
  • 看源码我们能知道出现验证异常的时候是执行的handleBindException这个方法

springboot validation 统一返回错误信息

上一篇:SpringBoot+MongoDB 实现图片存取


下一篇:java 异步