Is there a generic spring-data Exception class to handle exceptions thrown in the repo layer? - spring

I'm using spring-data-jpa to read/write to my DB. I've read through the documentation for spring-data and the one thing that I can't seem to locate is how it handles exceptions.
I am looking to catch any type of exception thrown by a repo action. Is there a way of doing this short of just wrapping the individual repo action in a try/catch and catching any RuntimeException? I'd rather avoid that as that is an even larger catch-all than I'd like.
Does spring-data wrap all exceptions in its own SpringDataException() or something similar? I've looked through the spring-data-commons jar as well as the spring-data-jpa jar and didn't find anything applicable.

Does spring-data wrap all exceptions in its own SpringDataException() or something similar
Yes, sort of. spring-data(-jpa) enable exception translation from JPA exceptions to Spring’s DataAccessException hierarchy:
From spring-data-jpa reference implementation:
...Beyond that, it activates persistence exception translation for all beans annotated with #Repository to let exceptions being thrown by the JPA persistence providers be converted into Spring’s DataAccessException hierarchy.
From Spring reference implementation:
Spring provides a convenient translation from technology-specific exceptions like SQLException to its own exception class hierarchy with the DataAccessException as the root exception. These exceptions wrap the original exception so there is never any risk that one might lose any information as to what might have gone wrong...
For more read about Spring DAO support

Related

Does Spring have any way of catching/handling ServletException?

I there any predefined way in Spring to catch or handle ServletException?
I mean any annotation or class that catches them and provide utility methods for them?
There are several techniques and approaches to handle Servlet Exceptions with Spring.
I can redirect you to this interesting link:
Exception Handling for REST with Spring
Exceptions can be managed at the DispatchServlet level, Controller level or application level. You can chose the method that better fit your needs.
Exception handling can be implemented per controller (using the old #ExceptionHandler or more recent and easy to use ResponseStatusException), or within global exception handler that centralize all exception management (using #ControllerAdvice)

Does it make sense to use PersistenceExceptionTranslationPostProcessor with Spring's JdbcTemplate?

Title speaks for itself.
Is PersistenceExceptionTranslationPostProcessor used solely for JPA implementations or is it relevant to use it with Spring's JdbcTemplate too?
And if there are two datasources needed each with their own JPA entity manager and transaction manager, do I still only need to specify one PersistenceExceptionTranslationPostProcessor for the entire application?
The auto-award bounty answer is wrong
~~~The correct answer is as follows~~~
I believe I've discovered the answer here:
http://www.deroneriksson.com/tutorials/java/spring/introduction-to-the-spring-framework/component-scanning-and-repository
The #Repository annotation can have a special role when it comes to converting exceptions to Spring-based unchecked exceptions. Recall that the JdbcTemplate handled this task for us. When we work with Hibernate, we’re not going to work with a Spring template that handles this conversion of Hibernate-based exceptions to Spring-based exceptions. As a result, in order to handle this conversion automatically, Hibernate DAOs annotated with #Repository will have their Hibernate exceptions rethrown as Spring exceptions using a PersistenceExceptionTranslationPostProcessor.
Further reading: http://www.deroneriksson.com/tutorials/java/spring/introduction-to-the-spring-framework/hibernate-daos
The paragraph above explicitly says:
Recall that the JdbcTemplate handled this task for us
So, to answer my own question, there is no need to use PersistenceExceptionTranslationPostProcessor with jdbcTemplate
Yes you can, The Spring exception translation mechanism can be applied transparently to all beans annotated with #Repository – by defining an exception translation bean post processor bean in the Context:
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
As per it doc
Bean post-processor that automatically applies persistence exception translation to any bean marked with Spring's #Repository
annotation, adding a corresponding
PersistenceExceptionTranslationAdvisor to the exposed proxy (either an
existing AOP proxy or a newly generated proxy that implements all of
the target's interfaces).
Translates native resource exceptions to Spring's DataAccessException hierarchy. Autodetects beans that implement the
PersistenceExceptionTranslator interface, which are subsequently asked
to translate candidate exceptions.
All of Spring's applicable resource factories (e.g. LocalContainerEntityManagerFactoryBean) implement the
PersistenceExceptionTranslator interface out of the box. As a
consequence, all that is usually needed to enable automatic exception
translation is marking all affected beans (such as Repositories or
DAOs) with the #Repository annotation, along with defining this
post-processor as a bean in the application context.
So you can use it with Jdbctemplate as well as with any Jpa vendor implementation
As per is doc All of Spring's applicable resource factories (e.g. LocalContainerEntityManagerFactoryBean) implement the PersistenceExceptionTranslator interface out of the box, I think you still need to use PersistenceExceptionTranslationPostProcessor, because it used to translate all errors generated during the persistence process (HibernateExceptions, PersistenceExceptions...) into DataAccessException objects.

What are the other use of Spring AOP except Logging and Exception handling?

Spring AOP and AspectJ are usually used for Exception handling and Logging. Is there any other feature for which we are using aspectJ and spring AOP.
Yes, transactional behavior is the first to come to mind. Take a look at the #Transactional annotation. You mark a method with the annotation and the container will take the necessary steps to start a transaction before your method executes and commit or roll back the transaction when it ends.
Security is another nice application of AOP. You can annotate a method to mark it as requiring certain permissions. For example, in a web application, you might have a few handler methods for requests that require the user to be an administrator. Instead of implementing that logic in each handler method, you extract it to some AOP advice and put a joinpoint at each of those methods.
Aspects can be used as any type of filter really. You can allow, prevent, modify access to a method.
Note that Spring's support for AOP is limited to method invocation join points.

What is "persistence exception translation" for #Repository beans

I was reading Spring with annotation part and I came across #Repositoryannotation
I read that #Repository beans differ from #Component beans in the sense that they are eligible for persistence exception translation.
Can somebody please elaborate what is meant by persistence exception translation?
Persistence Exception Translation is the process of converting low level persistence exceptions into high level Spring exceptions.
From the SpringSource Site:
Common data access exceptions. Spring can wrap exceptions from your
O/R mapping tool of choice, converting them from proprietary
(potentially checked) exceptions to a common runtime
DataAccessException hierarchy. This allows you to handle most
persistence exceptions, which are non-recoverable, only in the
appropriate layers, without annoying boilerplate catches/throws, and
exception declarations. You can still trap and handle exceptions
anywhere you need to. Remember that JDBC exceptions (including DB
specific dialects) are also converted to the same hierarchy, meaning
that you can perform some operations with JDBC within a consistent
programming model.
One of the major benefits of this is that exceptions are turned into Runtime Exceptions, in effect you are not required to add the throws declaration to your methods signature.
http://static.springsource.org/spring/docs/2.5.x/reference/orm.html
It provides a consistent exception hierarchy regardless of the database type or persistence methodology/technology you're using.
You get the same exceptions for the same types of errors regardless of whether you're using Oracle vs MySQL or JPA vs JDBC.
Take a look at the SQLErrorCodeSQLExceptionTranslator and sql-error-codes.xml.
sql-error-codes.xml is particularly interesting as you can see all the various vendor-specific error codes and what exception in the hierarchy they map to.
The Spring exception translation mechanism can be applied transparently to all beans annotated with #Repository – by defining an exception translation bean post processor bean in the Context

Can I use spring DataAccessException directly in service layer

Can I use spring DataAccessException directly in service layer?. Is this a good practice/design to spread a frame work class in service layer?.
OR
should i catch DataAccessException in dao layer and rethrow it as some more generic Exception?
I think it's fine for the DAO layer to throw that exception. The service layer already knows about the persistence layer, so no additional dependencies are created.
It is good to map/wrap the DataAccessException (thrown from DAO layer) into application specific exception hierarchy (in service layer) so that the dependent/calling layer has to just deal with your application specific exception classes.
Personally, I catch all checked exceptions in the service layer and throw my own ServiceExceptions initializing them with the catched exception. This way, the exception information is not lost and Controllers don't need to deal with low-level exceptions. But there's no need to do this in the DAO layer.
There's a pretty good chapter on exception handling in "Effective Java" (J. Bloch), it's a good read, as well as the rest of the book. Item 61 deals with this question.
http://books.google.de/books/about/Effective_Java.html?id=Ft8t0S4VjmwC

Resources