加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

java – Spring数据异常处理

发布时间:2020-12-15 01:39:23 所属栏目:大数据 来源:网络整理
导读:我正在使用Spring Data-JPA开发一个项目.我需要在JpaRepository方法调用中处理一些异常. 在下面的代码中,我需要拦截主键违规错误,但我无法直接捕获异常.在我的例子中,当发生这种异常时,存储库层(JpaRepository)抛出UnexpectedRollbackException异常.我需要在

我正在使用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关于那些方法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读