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

Spring boot rest API中缺少路径变量时捕获异常,spring-boot,Spring Boot,如果RESTAPI URL中缺少path变量,如何处理或生成异常 我使用的是spring 4.3.2。我的印象是将抛出MissingPathVariableException。但它并没有抛出那个例外 控制器方法: @RequestMapping(method = RequestMethod.GET, value="favorite/all/{userCd}") public List<UserApplicationDTO> getAllUserFavorites(@PathVari

如果RESTAPI URL中缺少path变量,如何处理或生成异常

我使用的是spring 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);

}
@RequestMapping(method=RequestMethod.GET,value=“favorite/all/{userCd}”)
公共列表getAllUserFavorites(@PathVariable(“userCd”)字符串userCd)引发MyException{
Validation.checkNotNull(userCd,message.getNotNullMessageUser());
返回userFavoriteService.getAllUserFavorites(userCd);
}
处理程序方法:

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

}
@覆盖
受保护的ResponseEntity handleMissingPathVariable(MissingPathVariableException ex、HttpHeaders、,
HttpStatus状态,WebRequest请求){
字符串错误=ex.getParameter()+“缺少参数”;
ErrorMessageHandler APIRROR=消息(HttpStatus.BAD_请求,例如getLocalizedMessage(),错误);
返回新的ResponseEntity(apiError,new-HttpHeaders(),HttpStatus.BAD_请求);
}

如果缺少path变量,则控制器将尝试将不带path变量的url映射到控制器方法。例如,在您的示例中,不带path变量的url可能是“app context”/favorite/all/。如果找不到具有该url的方法,它将生成404错误。您可能必须编写一个全局异常处理程序。看看这篇博文<代码>https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc

如果缺少path变量,则控制器将尝试将不带path变量的url映射到控制器方法。例如,在您的示例中,不带path变量的url可能是“app context”/favorite/all/。如果找不到具有该url的方法,它将生成404错误。您可能必须编写一个全局异常处理程序。看看这篇博文<代码>https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc