How to handle JSON Parse Error in Spring Rest Web Service

Viewed 23237

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.

2 Answers

You also can extend ResponseEntityExceptionHandler and override the method handleHttpMessageNotReadable (example in Kotlin, but very similar in Java):

override fun handleHttpMessageNotReadable(ex: HttpMessageNotReadableException, headers: HttpHeaders, status: HttpStatus, request: WebRequest): ResponseEntity<Any> {
    val entity = ErrorResponse(status, ex.message ?: ex.localizedMessage, request)
    return this.handleExceptionInternal(ex, entity as Any?, headers, status, request)
}
Related