Annette Rego
Annette Rego

Reputation: 21

Catch exception when path variable is missing in rest API

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

Answers (2)

dbaltor
dbaltor

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

vijayanand
vijayanand

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

Related Questions