I want to know how can I handle internal server error type exceptions in Spring Data Rest such as JPA exceptions etc. due to a malformed request or a database crash. I did some
You can do it like this:
@ControllerAdvice(basePackageClasses = RepositoryRestExceptionHandler.class)
public class GenericExceptionHandler {
@ExceptionHandler
ResponseEntity handle(Exception e) {
return new ResponseEntity("Some message", new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
}
This is the way I do it for all request validation errors,
@RestControllerAdvice
public class ApplicationExceptionHandler {
@ExceptionHandler
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseBean handle(MethodArgumentNotValidException exception){
StringBuilder messages = new StringBuilder();
ResponseBean response = new ResponseBean();
int count = 1;
for(ObjectError error:exception.getBindingResult().getAllErrors()){
messages.append(" "+count+"."+error.getDefaultMessage());
++count;
}
response.setMessage(messages.toString());
return response;
}
}
where ResponseBean
is my application specific class.
For JPA errors , exceptions are RuntimeExceptions and top level Exception is - org.springframework.dao.DataAccessException
.
If you wish to send a generic message to client, there is no need to catch - rethrow in your DAO, Service or Controller Layer. Just add an exception handler as above for DataAccessException
and you are done.
If you wish to set specific messages for client for specific exceptions, you need to write an application specific exception hierarchy extending DataAccessException
, lets say MyAppJPAException
. You need to catch - DataAccessException
in your application code ( either at DAO, Service or Controller layer ) and re throw MyAppJPAException
. MyAppJPAException
should have a custom message field where you should set your custom message before re throwing. In MyAppJPAException
handler, you set that message in response and can set HTTP Status as - HttpStatus.INTERNAL_SERVER_ERROR