Spring数据异常处理

 李磊g114826 发布于 2023-02-05 10:23

我正在使用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.以下是有关这些方法的信息.

1 个回答
  • 无论您在何处处理异常,都可以选择查看getMostSpecificCause()getRootCause()方法UnexpectedRollbackException.以下是有关这些方法的信息.

    2023-02-05 10:25 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有