简体   繁体   English

使用ControllerAdvice进行不确定性的Spring Boot验证

[英]Spring Boot Validation with ControllerAdvice Not Behaving Deterministically

I have the following setup 我有以下设置

@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
        );
    }

}

This is roughly the @RestController that throws well formatted validation exceptions 这大概是@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
    }
}

And POJOs that I want to bind have JSR-303 validation annotations on them, Spring correctly validate them at Bind time during request parameter binding 我要绑定的POJO上具有JSR-303验证注释,Spring在请求参数绑定期间的绑定时间正确验证了它们

However ... while I got this setup to work for a while - then Spring randomly started to bypass the @RestController and @ControllerAdvice 但是...虽然我让此设置工作了一段时间-然后Spring随机开始绕过@RestController@ControllerAdvice

It appears that now I am receiving org.springframework.web.bind.MethodArgumentNotValidException ... ie the request is getting short circuited 看来我现在正在接收org.springframework.web.bind.MethodArgumentNotValidException ...即请求正在短路

I am running Spring Boot 1.5.4.RELEASE ... 我正在运行Spring Boot 1.5.4.RELEASE ...

EDIT following suggestion from another thread , I added 根据另一个线程的建议编辑 ,我添加了

@Order(Ordered.HIGHEST_PRECEDENCE)

to the controller advice ... it only served to make matters worse. 向管制员的建议...只会使情况变得更糟。 now there is absolutely no validation errors - the client only receives a blank message (which was the symptom of the problem for a while before the current issue surfaced without any code changes) 现在绝对没有验证错误-客户端仅收到一条空消息(这是问题的症状,在当前问题浮出水面之前,没有任何代码更改)

Ok it turns out 好,结果

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 Please go ahead and make sure @RequestBody is declared IMMEDIATELY before BindingResult tl; dr请继续并确保在BindingResult之前 @RequestBody声明为IMMEDIATELY

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM