Node.js Unhandled Rejection Error

By | July 14, 2018
Questions:

I’m getting an Unhandled Rejection error in my code but the trace won’t tell me what’s causing it. I think it’s the webp.cwebp call that is causing the issue. When I run the code, I successfully convert the image and log status and then run into the Unhandled Rejection. It seems like I don’t enter into the last two .then(() blocks since no console messages get logged from them.

How can I properly handle the rejection error to avoid this error? I’ve tried inserting and removing status in the resolve() and reject() statements but it doesn’t seem to fix it.

 // Download image file from Google Cloud Storage bucket.
 return file.download({ destination: tempLocalFilename })
  .catch((err) => {
    console.error('Failed to download file.', err);
    return Promise.reject(err);
  })
  .then(() => {
    console.log(`Image ${file.name} has been downloaded to ${tempLocalFilename}.`);

    // Convert PNG to webp using webp-converter.
    return new Promise( (resolve, reject) => {
        webp.cwebp(tempLocalFilename, newLocalFilename, "-q 80", status => {
             console.log(status);

             if (status === '100') {
                 resolve();
             } else {
                 reject(status);
             }
           }
         );
       });
  })
  .then(() => {
    console.log(`Image ${file.name} has been converted.`);

    // Upload the converted image back into the bucket.
    return file.bucket.upload(newLocalFilename, { destination: file.name })
      .catch((err) => {
        console.error('Failed to upload converted image.', err);
        return Promise.reject(err);
      });
  })
  .then(() => {
    console.log(`Converted image has been uploaded to ${file.name}`);

    // Delete the temporary file.
    return new Promise((resolve, reject) => {
      fs.unlink(tempLocalFilename, (err) => {
        if (err) {
          reject(err);
        } else {
          resolve();
        }
      });
    });
  });
Answers:

Leave a Reply

Your email address will not be published. Required fields are marked *