Spring 数据异常处理 [英] Spring Data Exception Handling
问题描述
我正在使用 Spring Data-JPA 进行一个项目.我需要处理 JpaRepository 方法调用中的一些异常.
I´m working on a project using Spring Data-JPA. I need to handle some exceptions in JpaRepository method calls.
在下面的代码中,我需要拦截主键违规错误,但我无法直接捕获异常.就我而言,当发生此类异常时,存储库层 (JpaRepository) 会抛出 UnexpectedRollbackException 异常.我需要在这个异常对象内部进行搜索,以确定问题的原因.
In the code bellow, I need to intercept primary key violations erros but I cannot catch the exception directly. In my case, when an exception of this kind occurs, the UnexpectedRollbackException exception is thrown by repository layer (JpaRepository). I need to search inside this exception object to determine what is the cause of the problem.
我想知道是否有更优雅"的方式来实现这一点.
I am wondering if there is a more "elegant" way to achieve this.
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;
}
谢谢!
更新:
下面的代码似乎好多了.
The code bellow seems to be much better.
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;
}
推荐答案
无论您在哪里处理异常,您都可以选择查看 getMostSpecificCause()
或 getRootCause()
UnexpectedRollbackException
的 code> 方法.这是有关这些方法的信息.
Wherever you handle the exception, you have the option of looking into the getMostSpecificCause()
or getRootCause()
methods of UnexpectedRollbackException
. Here is information about those methods.
这篇关于Spring 数据异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!