How to handle JPA unique constraint violations?

后端 未结 8 1813
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-05 14:05

When a unique constraint is violated, a javax.persistence.RollbackException is thrown. But there could be multiple reasons to throw a RollbackException

8条回答
  •  长情又很酷
    2020-12-05 14:20

    This might very late for you but here's how I solved it for PostGres.

    catch (DataIntegrityViolationException e) {
    
                for (Throwable t = e.getCause(); t != null; t = t.getCause()) {
    
                    if (PSQLException.class.equals(t.getClass())) {
                        PSQLException postgresException = (PSQLException) t;
    
                        // In Postgres SQLState 23505=unique_violation
                        if ("23505".equals(postgresException.getSQLState())) {
                            throw new CustomDataAlreadyExistsException("YourErrorCode", e);
                        }
                    }
                }
                throw new SomeOtherException("YourErrorCode2", e);
    
            }
    

提交回复
热议问题