I'm trying to implement rollback mechanism for saving image to AWS/S3 and also Its metadata to the AWS/RDS. But I got confused about handling exceptions. Spring documentation is not clear about throwing exceptions.
I want to delete S3 record if I Can't save metadata to the RDS.
Image img = s3Service.saveImageToS3(file, description);
img = rdsRepository.save(img);
// couldn't save to RDS, so rollback from S3
if(img.getId()==0){
s3Service.deleteImageFromS3(img);
return new ResponseEntity<>(img, HttpStatus.INTERNAL_SERVER_ERROR);
}else {
return new ResponseEntity<>(img, HttpStatus.CREATED);
}
rdsRepository
which I used above, extends "org.springframework.data.repository.CrudRepository"
public interface RdsRepository extends CrudRepository<Image, Long> {
Image class:
@Entity(name="Image")
@Data
@AllArgsConstructor @NoArgsConstructor
public class Image {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
As far as I know, CrudRepository.save()
method can throws only unchecked exceptions. Because of that I shouldn't catch them. Is this approach correct? If yes, What can be alternative solution?