当我尝试捕获DataIntegrityViolationException
并将其转换为我的自定义异常时,不执行catch块。
作为一个例子,我使用了以下代码: guide
结果,ServicePointRepository
抛出在我的控制器层处理的DataIntegrityViolationException
,运行时的代码似乎避免了catch阻塞。
我做错了什么?
这是PersistenceService的代码:
@Autowired
private ServicePointRepository servicePointRepository;
@Autowired
private BusinessExceptionFactory businessExceptionFactory;
@Autowired
private TransactionTemplate transactionTemplate;
@Override
public String save(final ServicePointDTO servicePointDTO) {
final ServicePointEntity servicePointEntity = mapToEntity(servicePointDTO);
return transactionTemplate.execute(status -> {
try {
return servicePointRepository.save(servicePointEntity).getId().toString();
} catch (DataIntegrityViolationException e) {
throw businessExceptionFactory.createBusinessException(AlreadyExistException.class, CommonError.ALREADY_EXIST);
}
});
}
答案 0 :(得分:0)
这是正确的方法:
@Override
public String save(final ServicePointDTO servicePointDTO) {
final ServicePointEntity servicePointEntity = mapToEntity(servicePointDTO);
try {
return transactionTemplate.execute(status -> servicePointRepository.save(servicePointEntity).getId().toString());
} catch (DataIntegrityViolationException e) {
throw businessExceptionFactory.createBusinessException(AlreadyExistException.class, CommonError.ALREADY_EXIST);
}
}
此外,此方法不应标记为@Transactional
答案 1 :(得分:0)
您需要定义一个PersistenceExceptionTranslationPostProcessor后处理器来代理您的存储库,并使用逻辑将专有异常转换为Spring DataAccessException层次结构。还要记住使用@Repository注释来标记存储库,以便检测和代理它们
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslatorPostProcessor(){
return new PersistenceExceptionTranslationPostProcessor();
}
或XML中的等价物