How to handle JSON Parse Error in Spring Rest Web Service
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)
}
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...
}
}