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

625
Views
Node.js (Express) error handling middleware with router

Here's my application structure:

- app.js
- routes
---- index.js

The ExpressJS app creates error handlers for development and production environments. Here's a code snippet from app.js:

app.use('/', routes); // routing is handled by index.js in the routes folder

//The following middleware are generated when you create the Express App

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('error.ejs', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

And inside of routes/index.js, where I handle all the routing:

var router = express.Router();

router.get('/', function (req, res) {
    someAsyncFunction(function(err, result) {
        if (err) throw err; // Handle this error
    }
});

module.exports = router;

I want the err to be passed to one of the error handlers instead of being thrown. How can I do this?

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You have to pass it to the next callback which is usually the third parameter in the route handler

var router = express.Router();

router.get('/', function (req, res, next) {
    someAsyncFunction(function(err, result) {
        if (err) {
            next(err); // Handle this error
        }
    }
});

module.exports = router;

calling next(err) will allow the error to be caught in a middleware down the chain with the following signature:

app.use(function (err, req, res, next){
    // do something about the err
});

Reference: http://expressjs.com/en/guide/error-handling.html

about 4 years ago · Santiago Trujillo Report

0

You can also create a middleware function to handle error in all routes without copying code everywhere, using arrow functions if you like.

1) Create a const function to handle errors.

either:

const handleErrorAsync = func => (req, res, next) => {
    func(req, res, next).catch((error) => next(error));
};

or

const handleErrorAsync = func => async (req, res, next) => {
    try {
        await func(req, res, next);
    } catch (error) {
        next(error);
    }
};

2) In your router use it for every request:

var router = express.Router();

router.get('/req1', handleErrorAsync(async (req, res, next) => {
   let result = await someAsyncFunction1();
   if(result){
       // res.send whatever
   }
}));
router.post('/req2', handleErrorAsync(async (req, res, next) => {
    let result = await someAsyncFunction2(req.body.param1);
    if(result){
        // res.send whatever
    }
}));
router.post('/req3', handleErrorAsync(async (req, res, next) => {
    let result = await someAsyncFunction3(req.body.param1, req.body.param2);
    if(result){
        // res.send whatever
    }
}));

module.exports = router;

3) In your server main app handle error:

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('error.ejs', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

This way you can reuse the error handling function in any route. Also, if there are any unhandled errors in any of your functions, this will catch them as well.

Try catch error handling taken from Here

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!