我有以下设置
@ControllerAdvice
public class AppControllerAdvice extends ResponseEntityExceptionHandler {
@ExceptionHandler({UserInputValidationException.class})
public ResponseEntity<UserInputValidationResponseBody> handleBadInputException(UserInputValidationException ex, WebRequest request) {
return new ResponseEntity<>(
new UserInputValidationResponseBody().setFieldErrors(ex.getFieldErrors()),
HttpStatus.BAD_REQUEST
);
}
}
这大致是@RestController
抛出格式良好的验证异常
@RestController
@RequestMapping("api")
public class MyController {
/**
per the answer, BindingResult must immediately follow the @RequestBody or the item being found
*/
@PostMapping
public ResponseEntity<?> foo(@Valid @RequestBody FormPOJO formBody, Principal principal, BindingResult bindingResult) {
// if bindingResult has errors, throw a UserInputValidationException
}
}
我想要绑定的POJO对它们进行JSR-303验证注释,Spring在请求参数绑定期间的绑定时正确验证它们
然而......当我让这个设置工作一段时间 - 然后Spring随机开始绕过@RestController
和@ControllerAdvice
现在看来我正在接收org.springframework.web.bind.MethodArgumentNotValidException
...即请求被短路
我正在运行Spring Boot 1.5.4.RELEASE ...
编辑根据another thread的建议,我添加了
@Order(Ordered.HIGHEST_PRECEDENCE)
给控制器建议......它只会让事情变得更糟。现在绝对没有验证错误 - 客户端只收到一条空白消息(在当前问题浮出水面之前,这是问题的症状,没有任何代码更改)
答案 0 :(得分:1)
好的结果是
An Errors/BindingResult argument is expected to be declared immediately after the model attribute, the @RequestBody or the @RequestPart arguments to which they apply: public org.springframework.http.ResponseEntity com.remo.api.portfolios.PortfolioController.put(java.security.Principal,org.springframework.validation.BindingResult,com.remo.api.portfolios.Portfolio
tl; dr 请继续并确保{strong> BindingResult 之前确认@RequestBody