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

309
Views
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 answers
Answer question

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 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!