2

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

}

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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}"})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.