March 21, 2018

Spring Data CrudRepository exceptions

Spring Data is awesome since it allows you to define simple interfaces that are automagically implemented by Spring to access the data.However, when you are used to writing your own boiler plate repository code it can be a bit strange to know when and if to catch exceptions. And what are those exceptions?! The documentation is not clear at all.
Good for us, vtor has a good little overview on the exception types.


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.