java – Spring数据异常处理

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

相关文章

这篇文章主要介绍了spring的事务传播属性REQUIRED_NESTED的原...
今天小编给大家分享的是一文解析spring中事务的传播机制,相...
这篇文章主要介绍了SpringCloudAlibaba和SpringCloud有什么区...
本篇文章和大家了解一下SpringCloud整合XXL-Job的几个步骤。...
本篇文章和大家了解一下Spring延迟初始化会遇到什么问题。有...
这篇文章主要介绍了怎么使用Spring提供的不同缓存注解实现缓...