我正在使用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);
}
return result;
}
最佳答案
无论您在何处处理异常,都可以选择查看UnexpectedRollbackException的getMostSpecificCause()或getRootCause()方法. Here is information关于那些方法.
原文地址:https://www.jb51.cc/spring/431663.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。