Spring TransactionTemplate不处理异常
问题描述:
当我尝试捕获DataIntegrityViolationException
并将其转换为我的自定义异常时,catch块不会执行。Spring TransactionTemplate不处理异常
正如我使用的代码从一个这样的示例: 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);
}
});
}
答
这是正确的方法:
@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
答
您需要定义PersistenceExceptionTranslationPostProcessor后处理器用逻辑代理您的存储库,将专有异常转换为Spring DataAccessException hie rachy。还记得与@Repository注解来标记库对它们进行检测和代理
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslatorPostProcessor(){
return new PersistenceExceptionTranslationPostProcessor();
}
或等值的XML