簡體   English   中英

使用ControllerAdvice進行不確定性的Spring Boot驗證

[英]Spring Boot Validation with ControllerAdvice Not Behaving Deterministically

我有以下設置

@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 ...

根據另一個線程的建議編輯 ,我添加了

@Order(Ordered.HIGHEST_PRECEDENCE)

向管制員的建議...只會使情況變得更糟。 現在絕對沒有驗證錯誤-客戶端僅收到一條空消息(這是問題的症狀,在當前問題浮出水面之前,沒有任何代碼更改)

好,結果

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請繼續並確保在BindingResult之前 @RequestBody聲明為IMMEDIATELY

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM