By working with Java EE, I defined a persistence layer that exposes serval DAOs (extending GenericDAO and by using Hibernate as ORM).
Then, I inject a certail DAO in order to work with it into another class.
@Inject
private MyDAO myDAO;
public void writeSomething(String key, String data) {
try {
myDAO.create(key, data);
} catch (ConstraintViolationException e) {
// BLOCK 1
} catch (Exception e) {
// BLOCK 2
}
}
Now, I'd like to test exceptions, by trying to write an entry duplication.
As expected, the application returns an error, but it isn't a ConstraintViolationException instance, but something else (in fact, EJBException).
11:42:19,065 ERROR [org.jboss.ejb3.invocation] (http-localhost-127.0.0.1-8080-3) JBAS014134: EJB Invocation failed on component MyDAO for method public java.lang.Object my.app.dal.genericdao.GenericDAOImpl.create(java.lang.Object) throws java.lang.IllegalStateException,javax.persistence.PersistenceException,org.hibernate.exception.ConstraintViolationException: javax.ejb.EJBException: javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: Duplicate entry
How can I to catch a specific exception thrown by myDAO according to the situation (in this case a constraint violation)?
You can catch the EJBException and unwrap it using exception.getCause(); to decide on further strategy.
However, I would not let the DAO throw PersistenceException into the application, wrapped or not. It will pollute your code with duplicate boilerplates with error handling on a different abstraction level.
It is advisable to handle the immediate failure inside the DAO and, if no recovery is possible, throw a business-centric application exception.
For cases, where a constraint violation is possible because you are trying to store a duplicate, consider querying for duplicates first and then modify and store the query result if appropriate. Relying on catching Exceptions instead is less readable and less efficient.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With