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.
The DataAccessException has a ton of subclasses which you can dig through, the hierarchy is extensive.
Catching and handling
The one I use most is EmptyResultDataAccessException. It is thrown when a result is expected but none is found. Basically if you try to CRUD something that does not exist.
As you can see on the picture it is no easy task navigating the spring exceptions. Use cases will differ in a lot of cases they can be split into two parts.
EmptyResultDataAccessException and “the rest”.
Sometimes an empty result is expected so catch that and handle as you wish. Then catch the DataAccessException for general error handling.