I use Spring and JPA along with HIbernate. When a PersistenceException is thrown, I want to catch it and return an error message so that it does not propagate to the caller.
@Transactional public String save(Object bean) { String error = null; try { EntityManager entityManager = getEntityManager(); for (int i = 0, n = entities.size(); i < n; i ++) { entityManager.merge(entities.get(i)); } } catch (PersistenceException e) { error = e.getMessage(); } return error; }
But I get an exception saying javax.persistence.RollbackException: Transaction marked as rollbackOnly. I get that the transaction should be rolled back after the exception, but how to return it when I caught the exception and do not want to throw it again?
source share