2017-01-04 21 views
0

如果在其他API URL中缺少路徑變量,如何處理或生成異常?其餘路徑變量缺失時捕獲異常API

我正在使用彈簧4.3.2。我的印象是MissingPathVariableException將被拋出。但它並沒有拋出這種例外。

控制器方法:

@RequestMapping(method = RequestMethod.GET, value="favorite/all/{userCd}") 

public List<UserApplicationDTO> getAllUserFavorites(@PathVariable("userCd") String userCd) throws MyException{ 

    Validation.checkNotNull(userCd,message.getNotNullMessageUser()); 
    return userFavoriteService.getAllUserFavorites(userCd); 
} 

處理程序方法:

@Override 
protected ResponseEntity<Object> handleMissingPathVariable(MissingPathVariableException ex, HttpHeaders headers, 
     HttpStatus status, WebRequest request) { 

    String error = ex.getParameter() + " parameter is missing"; 
    ErrorMessageHandler apiError =message(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), error) ; 
    return new ResponseEntity<Object>(apiError, new HttpHeaders(), HttpStatus.BAD_REQUEST); 

} 

回答

0

如果路徑變量缺失,則控制器將嘗試將URL映射而不路徑變量到控制器的方法。例如,在你的情況下,沒有路徑變量的url可能是「app-context」/ favorite/all /。如果它沒有找到具有該網址的方法,則會生成404錯誤。您可能必須編寫全局異常處理程序。看看這篇博文。 https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc