I am a beginner in Spring REST and was implementing the exception handling in Spring REST. Following is the Controller code which is throwing a custom exception
@RequestMapping(value = "/getAllCountries", method = RequestMethod.GET, headers = "Accept=application/json") public Country getCountries() throws CountryNotFoundException{ throw new CountryNotFoundException(); //List<Country> listOfCountries = countryService.getAllCountries(); // return listOfCountries; } @ExceptionHandler(CountryNotFoundException.class) public ResponseEntity<ErrorMessage> handleException(HttpServletRequest req, Exception e) { ErrorMessage error = new ErrorMessage("Custom handler message "+e.toString(), req.getRequestURI()); return new ResponseEntity<ErrorMessage>(error,HttpStatus.NOT_FOUND); } Despite this the handler is not executing and I am getting the below exception:
HTTP Status 500 - Request processing failed; nested exception is org.arpit.java2blog.exception.CountryNotFoundException Can someone please let me know are there any other configurations which need to be taken care of for the handler to execute?
EDIT: When I change the parameter for ResponseEntity to String then it works but not with ErrorMessage. Why is this behaviour happening?
CountryNotFoundExceptionis not aRuntimeExceptionResponseEntity<String> handleCountryNotFound(CountryNotFoundException e){ return ResponseEntity.status(404).entity("not found").build()}and then see if it is being called/captured at all?CountryNotFoundExceptionto extendException?