Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block

I am getting following error in my Node-Express App

UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 4)

To say the least, I have created a helper function which looks something like this

const getEmails = (userID, targettedEndpoint, headerAccessToken) => {     return axios.get(base_url + userID + targettedEndpoint,  { headers: {"Authorization" : `Bearer ${headerAccessToken}`} })     .catch(error => { throw error}) } 

and then I am importing this helper function

const gmaiLHelper = require("./../helper/gmail_helper") 

and calling it inside my api route like this

router.get("/emailfetch", authCheck, async (req, res) => {   //listing messages in users mailbox    let emailFetch = await gmaiLHelper.getEmails(req.user._doc.profile_id , '/messages', req.user.accessToken)   .catch(error => { throw error})   emailFetch = emailFetch.data   res.send(emailFetch) }) 

From my end, I think I am handling the error by using catch block.

Question: Can someone explain me why I am getting the error and how can I fix it?

like image 786
anny123 Avatar asked Dec 27 '18 05:12

anny123


People also ask

How do you handle the promise rejection while using async await and promises?

Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.

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.

How do you get a rejected promise in async await?

If the Promise is rejected, the await expression throws the rejected value. If the value of the expression following the await operator is not a Promise , it's converted to a resolved Promise. An await splits execution flow, allowing the caller of the async function to resume execution.

How do you deal with unhandled rejection?

If an error condition arises inside a promise, you “reject” the promise by calling the reject() function with an error. To handle a promise rejection, you pass a callback to the catch() function. This is a simple example, so catching the rejection is trivial.


2 Answers

.catch(error => { throw error}) is a no-op. It results in unhandled rejection in route handler.

As explained in this answer, Express doesn't support promises, all rejections should be handled manually:

router.get("/emailfetch", authCheck, async (req, res, next) => {   try {   //listing messages in users mailbox      let emailFetch = await gmaiLHelper.getEmails(req.user._doc.profile_id , '/messages', req.user.accessToken)     emailFetch = emailFetch.data     res.send(emailFetch)   } catch (err) {     next(err);   } }) 
like image 170
Estus Flask Avatar answered Sep 27 '22 23:09

Estus Flask


I suggest removing the below code from getMails

 .catch(error => { throw error}) 

In your main function you should put await and related code in Try block and also add one catch block where you failure code.


you function gmaiLHelper.getEmails should return a promise which has reject and resolve in it.

Now while calling and using await put that in try catch block(remove the .catch) as below.

router.get("/emailfetch", authCheck, async (req, res) => {   //listing messages in users mailbox  try{   let emailFetch = await gmaiLHelper.getEmails(req.user._doc.profile_id , '/messages', req.user.accessToken) } catch (error) {   // your catch block code goes here }) 
like image 34
Sumer Avatar answered Sep 27 '22 22:09

Sumer