Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

225
Views
Why re-throwing error in catch block having TypeError

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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)
      }
    }
  })
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!