Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

310
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda