Home > Enterprise >  Spring, catch exception
Spring, catch exception

Time:05-22

I have small problem. I can't catch exception in method. I need to catch ConstraintViolationException to process it. Somebody know why it happens?

@Transactional(rollbackFor = Exception.class)
public void saveCustomer(Customer customer) {
    Session session = sessionFactory.getCurrentSession();
    try {
        session.save(customer);
    } catch (Throwable e) {
        log.debug(e);
        // Process exception
    }
}

CodePudding user response:

Based on question, it looks like session.save(..) is not throwing exception at all but rather persisting entity into db. Can you check if your customer object got saved into db after this method got executed.

You might be looking for unique key constraint violation or some sort but session.save(..) is saving entity into db. You might need to check your how you have defined your Customer entity as well.

CodePudding user response:

I ran into similar problem some days ago. I looked at the StackTrace and used PersistenceException.

Try it:

@Transactional(rollbackFor = Exception.class)
public void saveCustomer(Customer customer) {
    Session session = sessionFactory.getCurrentSession();
    try {
        session.save(customer);
    } catch (PersistenceException e) {
        log.debug(e);
        // Process exception
    }
}
  • Related