Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

227
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda