Reputation: 21
How do I handle or generate an exception if path variable is missing in rest API URL?
I am using spring 4.3.2. I was under the impression that MissingPathVariableException
will be thrown. But it's not throwing that exception.
Controller method:
@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);
}
Handler method:
@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);
}
Upvotes: 2
Views: 6054
Reputation: 3383
For a MissingPathVariableException
to be thrown, the request has to match the request mapping. Change your RequestMapping annotation as follows:
@RequestMapping(method = RequestMethod.GET,
value={"favorite/all", "favorite/all/", "favorite/all/{userCd}"})
Upvotes: 0
Reputation: 238
If the path variable is missing, then the controller would try to map the url without the path variable to the controller method. For example in your case the url without the path variable might be "app-context"/favorite/all/. And if it doesn't find a method with that url, it would generate 404 error. You might have to write a global exception handler. Take a look at this blog post. https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
Upvotes: 1