Search code examples
javascriptnode.jsscopetry-catchcloudinary

Node / JavaScript get try variable in catch block to delete cloudinary image when there is an error


This code works fine to upload image to cloudinary. Let's say the image is uploaded but then there is a mongodb error. Then I want to delete the image that is already at cloudinary but how can i get the value of "cloudinary_id" in my catch block?

createGalery: async (req, res) => {
    try {
      const result = await cloudinary.uploader.upload(req.file.path, {
        folder: 'Test'
      });

      let image = result.secure_url;
      let cloudinary_id = result.public_id;

      const newGalery = new Galery({
        image,
        cloudinary_id,
      });
      await newGalery.save();
      res.json({ msg: 'successful' });
    } catch (err) {
      try {
        console.log(cloudinary_id);
        // How to delete when mongodb save fails?
        //await cloudinary.uploader.destroy(result.public_id);
      } catch {
        return res.status(500).json({ msg: err.message });
      }
      return res.status(500).json({ msg: err.message });
    }
  }

Solution

  • Nest your try blocks:

    createGalery: async (req, res) => {
      try {
        const result = await cloudinary.uploader.upload(req.file.path, {
          folder: 'Test'
        });
        const cloudinary_id = result.public_id;
    
        try {
          const newGalery = new Galery({
            image: result.secure_url,
            cloudinary_id,
          });
          await newGalery.save();
        } catch (mongoErr) {
          console.log(`Removing ${cloudinary_id} due to failed save`);
          await cloudinary.uploader.destroy(cloudinary_id);
          throw mongoErr;
        }
    
        res.json({ msg: 'successful' });
      } catch (err) {
        return res.status(500).json({ msg: err.message });
      }
    }