Why re-throwing error in catch block having TypeError

303 Views Asked by At

I have a route handler in express.js and inside it, I am calling an asynchronous function which should return me some value. I am using bluebird promises to handle the promises. Below is a sample code.

router.js
---------
router.post('/endpoint', (req, res) => {
 return Promise.try(() => serviceFile.validate())
        .then(() => {
            console.log('Response: ', response);   
})
        .catch((error) => {
             console.log('Error: ', error) // TypeError: expecting a function but got [object Promise]
})

})


serviceFile.js
--------------
async function validate() {
  return Promise.try(() => axios.post('/endpoint'))
         .then((response) => response.data)
         .catch((error) => {
         console.log('Error: ', error.response.data) // successfully printing the error data object
          throw error; 
}) 
}

When I call the validate() in the Service.js file, it fails the request (which I want) and successfully prints the error. But I don't want to handle the error here, so I re-throw it and expects to handle it in the router.js file. But in the router.js file, I am getting error as undefined and it says, TypeError: expecting a function but got [object Promise]

I am not getting any clue where I am doing wrong. Any help would be greatly appreciated.

1

There are 1 best solutions below

3
alilland On

its sort of unclear what serviceFile.validate does unless thats the second function you listed, this might be a more clear way of using promises

router.post('/endpoint', async (req, res) => {
  try {
    const response = await serviceFile.validate()
    console.log('Response: ', response);
  } catch (err) {
    console.log('Error: ', error)
  }
})

function validate () {
  return new Promise(async (resolve, reject) => {
    try {
      const res = await axios.post('/endpoint')
      resolve(res.data)
    } catch (err) {
      if (err.response && err.response.data) {
        reject(err.response.data)
      } else {
        reject(err)
      }
    }
  })
}