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.