以下方法尝试将数据写入DB(firmRepository.save()
)和ElasticSearch(firmSearchRepository.save()
)。
问题是如果数据库保存失败,我不想写入ES存储库。我试图用DataAccessException
捕获异常,但通过我的测试,我看到了诸如唯一约束违规之类的例外 - > ElasticSearch中的通过和持久性仍然执行。
@Override
public FirmDTO save (FirmDTO firmDTO) {
log.info("Database Request to save Firm: {}", firmDTO.getFirmId());
Firm firm = firmMapper.firmDTOtoFirm(firmDTO);
try {
firm = firmRepository.save(firm);
firmSearchRepository.save(firm);
return firmMapper.firmToFirmDTO(firm);
} catch (DataAccessException ex) {
log.error(ex.getLocalizedMessage());
return null;
}
}
有没有办法捕获与SQL相关的特定异常?
答案 0 :(得分:1)
使用saveAndFlush()
JPA存储库方法可以捕获Spring Data异常。
@Override
@Transactional
public FirmDTO save (FirmDTO firmDTO) {
log.info("Database Request to save Firm: {}", firmDTO.getFirmId());
Firm firm = firmMapper.firmDTOtoFirm(firmDTO);
try {
firm = firmRepository.saveAndFlush(firm);
firmSearchRepository.save(firm);
return firmMapper.firmToFirmDTO(firm);
} catch (DataAccessException ex) {
log.error("my exception");
log.error(ex.getLocalizedMessage());
return null;
}
}