Dhruv
Dhruv

Reputation: 10693

How to override default Spring JPA exception translator behavior?

I don't know if this approach is the best or not. But I have a requirement where I need to handle Spring JPA repository (DAO layer) exception. Handle in the sense may be propogate it to UI or may be do some logic on service layer.

Now as per present scenario from over repositories all our SQL Exception got wrapped into Runtime exception DataAccessException.

Now one way if I want to propogate this Exceptions to my UI layer than I catch this Runtime Exception on Service layer and wrap this exception into my Custom Exception and then propogate it. But I don't want to catch this Runtime exception. Is there any way that I override the Exception translator behavior of Spring JPA and make it wrap all SQL exception into my Custom Checked exception? If I am able to do this, in my views this approach is better.

Upvotes: 2

Views: 3757

Answers (2)

Ashish
Ashish

Reputation: 3652

Spring JPA translates all exceptions to Spring's DataAccessException, there is no harm in handling these exception in your DAO layer. IMO, even if you can override the spring JPA's exception translation behaviour, why would you do that? as there is no business valur associated with that.

similiar discussion in below thread: Exception Handling Strategy with Spring/JPA/JSF

Upvotes: 0

Jignesh.Raj
Jignesh.Raj

Reputation: 5987

question about TransactionSystemException: this exception was thrown when exiting @Transactional method in order to indicate that transaction had been rolled back.

If you want to reliably catch constraint violations, you need to do it around transaction, not inside it. For example, by using programmatic transaction demarcation inside saveUser() method instead of @Transactional, or by adding try-catch clause to the top-level method.

or you should visit

JPA JPA

Upvotes: 1

Related Questions