2017-07-16 31 views
0

我有以下設置春季啓動驗證與ControllerAdvice行爲不確定性地

@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 
@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的@RestController -303驗證註釋,Spring在請求參數綁定期間在綁定時正確驗證它們

但是... w往往微不足道我得到這個設置到工作一段時間 - 然後隨機春季開始繞過@RestController@ControllerAdvice

看來,現在我收到org.springframework.web.bind.MethodArgumentNotValidException ...即要求越來越短路

我運行春季啓動1.5.4.RELEASE ...

編輯以下從another thread的建議,我加

@Order(Ordered.HIGHEST_PRECEDENCE) 

對控制器的建議...它只會使事情變得更糟。現在是絕對沒有驗證錯誤 - 客戶端只收到一個空的消息(這是問題的症狀一會兒之前,在當前問題浮出水面時無需更改任何代碼)

回答

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;博士請繼續前進,確保@RequestBody聲明立即前BindingResult