The following methods tries to write data to DB ( firmRepository.save()
) and to ElasticSearch ( firmSearchRepository.save()
).
The problem is that I do not want to write to ES repository if the DB save failed. I am trying to catch the exception with DataAccessException
, but through my tests I see that such exceptions as unique constraint violation -> get through and persistence in ElasticSearch still executes.
@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;
}
}
Is there way to catch those specific exceptions related to SQL?
Using the saveAndFlush()
JPA repository method made catching Spring Data exceptions possible.
@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;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.