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

164
Vistas
Problem with handling errors in Express framework

I am currently working on node.js + express + mongoDB project. I am trying to handle error that occurs when data cannot be received from database. I am simulating this by terminating mongod process in console and calling .get in Postman. Sadly instead of getting an error in Postman I only get Unhandled Promise Rejection in console. I read a lot of posts about error handling and implemented it according to this guide: https://expressjs.com/en/guide/error-handling.html. I would be grateful for any idea of how can I fix this.

The code:

Printing all courses:

router.get("/", async (req, res, next) => {
  try {
    const courses = await Course.find().sort("dishName");
    res.send(courses);
  } catch (ex) {
    next(ex);
  }
});

error.js:

module.exports = function (err, res, req, next) {
  res.status(500).send(`500 Error`);
};

index.js

const error = require(`./middleware/error`);

app.use(error);

app.use(error) is placed as the last app.use

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

There is a minor mistake in your code. The order of the req and res parameters in the error handler function should not be changed.

// Error.js
module.exports = function (err, req, res, next) {
  res.status(500).send(`500 Error`);
};
over 4 years ago · Santiago Trujillo 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