Reputation: 2238
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?
Upvotes: 0
Views: 4307
Reputation: 790
Try this one
import com.fasterxml.jackson.annotation.JsonProperty;
public class ErrorMessage {
@JsonProperty
private final String message;
@JsonProperty
private final String requestURI;
public ErrorMessage(String message, String requestURI) {
this.message = message;
this.requestURI = requestURI;
}
}
Upvotes: 3
Reputation: 1671
Please follow my post on exception handling. I've created sample project for more detailed reference which can found here
Upvotes: 0