处理JPA中的ConstraintviolationException

时间:2017-10-19 11:33:17

标签: java jpa spring-boot

我的问题很常见,但我似乎无法找到任何解决方案。我搜索了很多,但没有找到任何东西

情况:

尝试插入导致外键冲突导致我的事务回滚的行。 无论我处理什么异常,它总是从我的休息终点抛出500,这是不可接受的

问题: 如何优雅地处理这个问题。以下是我的代码无效

@Transactional(dontRollbackOn={InvalidModelException.class,PersistenceException.class,ConstraintViolationException.class,MySQLIntegrityConstraintViolationException.class})
    @Override   
    public PointAudit createPointAudit(PointAudit pointAudit) throws EmptyModelException, InvalidModelException {
        if(pointAudit != null) {
            try {
                this.entityManager.persist(pointAudit);
                this.entityManager.flush();
            }

            catch(RollbackException x) {
                LOGGER.error(x.getMessage(), x);
            }
            catch(PersistenceException x) {
                if(x.getCause() instanceof ConstraintViolationException) {
                    if(x.getCause().getCause() instanceof MySQLIntegrityConstraintViolationException)
                    {
                        MySQLIntegrityConstraintViolationException e = (MySQLIntegrityConstraintViolationException)x.getCause().getCause();
                        if(e.getMessage().contains("USER_ID")) {
                            throw new InvalidModelException("Invalid user is provided");
                        }
                        else {
                            if(e.getMessage().contains("STATUS")) {
                                throw new InvalidModelException("Invalid status is provided");
                            }
                            else {
                                if(e.getMessage().contains("CHANNEL")) {
                                    throw new InvalidModelException("Invalid channel is provided");
                                }
                                else {
                                    if(e.getMessage().contains("ACTION")) {
                                        throw new InvalidModelException("Invalid action is provided");
                                    }
                                }
                            }
                        }
                    }

                }
                else {
                    while( !(x.getCause() instanceof RollbackException) || x.getCause() == null) {
                        LOGGER.error(x.getMessage(), x);
                    }
                }
            }
        }
        else {
            throw new EmptyModelException("Point Audit is empty");
        }
        return pointAudit;
    }

如果需要进一步的代码,请告诉我

0 个答案:

没有答案