Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js Unhandled Rejection Error

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();
        }
      });
    });
  });
like image 489
swigganicks Avatar asked Jul 13 '18 03:07

swigganicks


People also ask

What is unhandled rejection in node JS?

The unhandledRejection event is emitted whenever a promise rejection is not handled. NodeJS warns the console about UnhandledPromiseRejectionWarning and immediately terminates the process. The NodeJS process global has an unhandledRejection event.

What is unhandled rejection error?

The unhandledrejection event is sent to the global scope of a script when a JavaScript Promise that has no rejection handler is rejected; typically, this is the window , but may also be a Worker . This is useful for debugging and for providing fallback error handling for unexpected situations.

How do you terminate the node process in unhandled promise rejection?

To terminate the node process on unhandled promise rejection, use the CLI flag '--unhandled-rejections=strict' (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) (node:89219) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated.

What is UnhandledPromiseRejectionWarning?

The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value. The Promise. reject() method returns a Promise object that is rejected with a given reason.


1 Answers

Q: I'm getting an Unhandled Rejection error, how can I properly handle the rejection error?

A: Like what the comments already said, a .catch(...) will stop your exception from bubbling up to become an unhandled rejection error.

Alternatively you can also insert reject handler function for each of the .then(...) clause. That is, for each .then() it should take in 2 functions, one for the happy path and the other for the bad path.

E.g.

  return new Promise( (resolve, reject) => {
        webp.cwebp(tempLocalFilename, newLocalFilename, "-q 80", status => {
             ...
           }
         );
       });
  })
  .then(/*happy path=*/() => {
    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);
      });
  },
  /*unhappy path=*/ (error) => { 
      console.log("oops something went wrong during uploading"); 
  })
  /*catch all rejection=*/
  .catch(error => {
       console.log("something bad happened somewhere, rollback!");
   });
like image 59
Samuel Toh Avatar answered Nov 03 '22 01:11

Samuel Toh