Categories
JavaScript Answers

How to fix UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block with JavaScript?

Spread the love

Sometimes, we want to fix UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block with JavaScript.

In this article, we’ll look at how to fix UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block with JavaScript.

How to fix UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block with JavaScript?

To fix UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block with JavaScript, we add a catch block.

For instance, we write

router.get("/emailfetch", authCheck, async (req, res) => {
  try {
    let emailFetch = await gmaiLHelper.getEmails(
      req.user._doc.profileId,
      "/messages",
      req.user.accessToken
    );
    emailFetch = emailFetch.data;
    res.send(emailFetch);
  } catch (error) {
    res.status(error.response.status);
    return res.send(error.message);
  }
});

to call getEmails which returns a promise.

If the returned promise is rejected, then the code in the catch block is run.

In the catch block, we run code to return a promise with error data.

Conclusion

To fix UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block with JavaScript, we add a catch block.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.