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

312
Vistas
How do I handle errors in a function called from a route handler in Express, NodeJS?

This may be extremely stupid, but I haven't found much about this because I don't understand how I should search this.

I have a route handler that may call different functions depending on some request parameters, and I would like to know what's the best way to deal with errors inside the functions in order to pass errors to the error handling middleware. Consider something like this:

router.get('/error/:error_id', (req, res, next) => {
    my_function();
}

function my_function(){
  // do something async, like readfile
  var f = fs.readFile("blablabla", function (err, data) {
      // would want to deal with the error
  });
}

If an error occurs during fs.readFile, how do I pass the error to next to forward it to the error middleware? The only solution is to pass the next param to the function function my_function(next){...}?

In case the function didn't call any async I/O operation, a simple try/catch in the route handler would be ok (i suppose), like this:

router.get('/error/:error_id', (req, res, next) => {
    try{
      my_function();
    } catch(e){
      next(e);
    };
}

function my_function(){
  // do stuff
  var f = fs.readFileSync("blablabla"); // possibly throws an error
}

Hope I make some sense.

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

0

You are totally correct that you should pass the next callback to my_function since fs.readFile is asynchronous.

router.get('/error/:error_id', (req, res, next) => {
  my_function(next);
}

function my_function(next) {
  fs.readFile("blablabla", function (err, data) {
    if (err) {
      next(err);
    } else {
      // Process the data
      // Don't forget to call `next` to send respond the client
    }
  });
}

By the way, you cannot do

var f = fs.readFile(...)

because fs.readFile is asynchronous. The data should be handled within the callback.

about 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