Home > database >  Running program when catch occurs
Running program when catch occurs

Time:12-31

I need to download images using this package - but sometimes, one of these images is corrupted. Here, one of the two sample images is corrupted and I'm adding a Math.random() to simulate this case. I'm now trying to restart the program once the .catch() occurs - the thing is the program runs infinitely then. How can I solve this?

My code is:

let imgArrays = ["https://upload.wikimedia.org/wikipedia/commons/d/dc/Gigi1.jpg", "https://mms.businesswire.com/media/20211119005773/fr/929256/5/Aries_Linden_mechanical_completion_11-19-2021.jpg"]

const runingImage = () => {


    const url = imgArrays[Math.floor(imgArrays.length * Math.random())];
    const path = 'img/image.jpg'
    options = {
        url: url,
        dest: path
    }
    download.image(options)
        .then(({
            filename
        }) => {
            console.log('Saved to', filename)
        }).catch(
            (err) => {
                console.log("running again");
                return runingImage();
            })
}

runingImage();

When I run it, it now only gives me:

running again
running again
...
Until I stops the console.

CodePudding user response:

It is unfortunate that you stepped into a trap all programmers have fallen (and still falling) at some point: missing files/folders

when you are still in the development stage, always print errors in catch statements. this is what you would get and eventually solve the problem yourself:

console.log(err)

ENOENT: no such file or directory, open 'img/image.jpg'

also there is this little mistake you are doing. you are creating a void type function and try to return its value which is always undefined

solution:

  1. create an img folder in the directory you put this file of yours.
  2. remove return word inside catch block leaving only runingImage();

CodePudding user response:

Remove the return statement. It should be like:

let imgArrays = ["https://upload.wikimedia.org/wikipedia/commons/d/dc/Gigi1.jpg", "https://mms.businesswire.com/media/20211119005773/fr/929256/5/Aries_Linden_mechanical_completion_11-19-2021.jpg"]
    
const runingImage = () => {
  const url = imgArrays[Math.floor(imgArrays.length * Math.random())]
  const path = 'img/image.jpg'
  options = {
      url: url,
      dest: path
  }
  download.image(options)
    .then(({
        filename
    }) => {
        console.log('Saved to', filename)
    }).catch(
        (err) => {
          console.log("running again")
    })
}

runingImage()
  • Related