@Valid + BindingResult 拦截接口错误信息
@Valid + BindingResult 拦截接口错误信息
###测试发现: HttpServletRequest request, HttpServletResponse response, 需要去掉,否则无法输出message错误消息
###测试发现 @Validated @Valid 这两个注解方法都可以。
public ResponseData testMvc(@Valid @RequestBody ReqVo reqVo,BindingResult bindingResult) { logger.info("testMvc controller params={}",GsonUtils.toJson(reqVo)); if (bindingResult.hasErrors()) { Optional<FieldError> error = bindingResult.getFieldErrors().stream().findFirst(); throw new InputErrorException(error.isPresent()?error.get().getDefaultMessage() : "参数输入错误"); } }
ReqVo.java
@NotBlank(message = "订单号不能为空")
private String orderNo;
@Range(min = 1,max = 4,message = "取值范围,1-4")
private int type;