Issue
I have this Spring Data CrudRepository
which handles the CRUD operations on a DB.
@Repository
public interface IUserRepository extends CrudRepository<User, String> {
}
User
is the Entity of a User table of my DB. CrudRepository
adds namely the following operations to the repository:
delete(String ID)
findOne(String ID)
save(User user)
As stated in the documentation, the delete and find operations throw IllegalArgumentException
in case the given id is null while the save operation doesn't throw any exception.
The problem is that the javadoc of the CrudRepository makes no mention about the other exceptions thrown by these operations. For example it doesn't tell that the delete(String ID)
operation throws a EmptyResultDataAccessException
in case the provided ID is nonexistent in the DB.
In the javadoc of the save(User user)
operation it's not clear which exceptions are thrown in case you insert a new User which breaks one data integrity constraint (on unique fields and foreign keys). Moreover it doesn't warn you whether you are writing a new or existent User: it just creates a new User or overwrites if existent (so it's a Insert + Update operation).
In a enterprise application I should be able to catch every throwable exception an operation can throw and I should read about that in the operation's javadoc.
Do you know any clear documentation about CrudRepository
exceptions?
Solution
Spring has built-in exception translation mechanism, so that all exceptions thrown by the JPA persistence providers are converted into Spring's DataAccessException - for all beans annotated with @Repository (or configured).
There are four main groups -
NonTransientDataAccessException - these are the exceptions where a retry of the same operation would fail unless the cause of the Exception is corrected. So if you pass non existing id for example, it will fail unless the id exists in the database.
RecoverableDataAccessException - these are the "opposite" of the previous one - exceptions which are recoverable - after some recovery steps. More details in the API docs
ScriptException - SQL related exceptions, when trying to process not well-formed script for example.
TransientDataAccessException - these are the exception when recovery is possible without any explicit step, e.g. when there is a timeout to the database, you are retrying after few seconds.
That said, the ideal place to find documentation about all exceptions - is in the API itself - just go through the hierarchy of DataAccessException.
Answered By - vtor