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

Time:10-16

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 });
    }
  }

CodePudding user response:

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 });
  }
}

CodePudding user response:

Move the declaration of your cloudinary_id variable outside of the try/catch block:

let cloudinary_id;

try {
  // ...
  cloudinary_id = result.public_id; // without the "let" keyword in front of it
  // ...
} catch (err) {
  console.log(cloudinary_id);

  if (cloudinary_id) {
    await deleteFromCloudinary(cloudinary_id);
    // if cloudinary_id is not set, the error was thrown
    // before setting it (i.e. while uploading to cloudinary)
  }
}
  • Related