Can't catch ConstraintViolationException

后端 未结 1 1243
野性不改
野性不改 2021-02-05 14:23

I can\'t seem to catch constraint violation Exception though I see it in the logs.

Entity

@Column(unique = true)
private String email;

相关标签:
1条回答
  • 2021-02-05 14:46

    It is wrapped in a EJBTransactionRolledbackException, so you should try to catch that one instead of ConstraintViolationException.

    The ConstraintViolationException is first wrapped by a PersistenceException, then by a RollbackException, and at last by an EJBTransactionRolledbackException.

    You should call the getCause() method of the Exception till you encounter the constraint violation or null, which would indicate that the exception is not due to a constraint violation. You can try something like:

    try {
        memberDao.create(newMember);
    } catch (EJBTransactionRolledbackException e) {
        Throwable t = e.getCause();
        while ((t != null) && !(t instanceof ConstraintViolationException)) {
            t = t.getCause();
        }
        if (t instanceof ConstraintViolationException) {
            // Here you're sure you have a ConstraintViolationException, you can handle it
        }
    }
    
    0 讨论(0)
提交回复
热议问题