在rest API中缺少路径变量时捕获异常

时间:2017-01-04 21:27:46

标签: spring-boot

如果在其他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);

}

1 个答案:

答案 0 :(得分:0)

如果缺少路径变量,则控制器将尝试将没有路径变量的url映射到控制器方法。例如,在您的情况下,没有路径变量的网址可能是&#34; app-context &#34; / favorite / all /。如果它没有找到带有该URL的方法,则会产生404错误。您可能必须编写全局异常处理程序。看一下这篇博客文章。 https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc