我正在使用Spring Data-JPA开发一个项目.我需要在JpaRepository方法调用中处理一些异常.
在下面的代码中,我需要拦截主键违规错误,但我无法直接捕获异常.在我的例子中,当发生这种异常时,存储库层(JpaRepository)抛出UnexpectedRollbackException异常.我需要在此异常对象内搜索以确定问题的原因.
我想知道是否有更"优雅"的方式来实现这一目标.
public Phone insert(Phone phone) throws BusinessException { Phone result = null; try{ result = phoneRepository.save(phone); } catch(UnexpectedRollbackException ex){ if((ex.getCause() != null && ex.getCause() instanceof RollbackException) && (ex.getCause().getCause() != null && ex.getCause().getCause() instanceof PersistenceException) && (ex.getCause().getCause().getCause() != null && ex.getCause().getCause().getCause() instanceof ConstraintViolationException)){ throw new BusinessException("constraint violation", ex); } } catch(Exception ex){ throw new OuvidorNegocioException("unknown error", ex); } return result; }
谢谢!
更新:
下面的代码似乎要好得多.
public Phone insert(Phone phone) throws BusinessException { Phone result = null; try{ result = phoneRepository.save(phone); } catch(UnexpectedRollbackException ex){ if(ex.getMostSpecificCause() instanceof SQLIntegrityConstraintViolationException){ throw new BusinessException("constraint violation", ex); } } catch(Exception ex){ throw new OuvidorNegocioException("unknown error", ex); } return result; }
Vidya.. 7
无论您在何处处理异常,都可以选择查看getMostSpecificCause()
或getRootCause()
方法UnexpectedRollbackException
.以下是有关这些方法的信息.
无论您在何处处理异常,都可以选择查看getMostSpecificCause()
或getRootCause()
方法UnexpectedRollbackException
.以下是有关这些方法的信息.