Issue
I have a rest web service developed with Spring Boot.I am able to handle all the exceptions that occur due to my code, but suppose the json object that the client posts is not compatible with the object that i want to desrialize it with, I get
"timestamp": 1498834369591,
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.http.converter.HttpMessageNotReadableException",
"message": "JSON parse error: Can not deserialize value
I wanted to know is there a way that for this exception, I can provide the client a custom exception message. I am not sure how to handle this error.
Solution
To customize this message per Controller, use a combination of @ExceptionHandler
and @ResponseStatus
within your Controllers:
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "CUSTOM MESSAGE HERE")
@ExceptionHandler(HttpMessageNotReadableException.class)
public void handleException() {
//Handle Exception Here...
}
If you'd rather define this once and handle these Exceptions globally, then use a @ControllerAdvice
class:
@ControllerAdvice
public class CustomControllerAdvice {
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "CUSTOM MESSAGE HERE")
@ExceptionHandler(HttpMessageNotReadableException.class)
public void handleException() {
//Handle Exception Here...
}
}
Answered By - Kyle Anderson
Answer Checked By - Gilberto Lyons (JavaFixing Admin)