[Node.js] Exception Handling in Node.js Express

Since Node.js is non-blocking, single-process, and single-threaded, once an exception is thrown, the entire service stops, making it very unstable. Here are the solutions:

  1. Make the program robust: Wrap all potentially exception-prone areas with try { } catch(){ }.
  2. Express error handling mechanism: As a commonly used Node.js framework, Express has its own error handling mechanism.
1
2
3
4
5
6
// Express' errorHandler
function errorHandler(err, req, res, next) {
    console.error(err.stack);
    res.status(500).send('Something broke!');
}
app.use(errorHandler);
  1. Use the domain module: First install the domain module with npm install domain
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// Domain exception handling
const domain = require('domain');

app.use(function(req, res, next) {
    var reqDomain = domain.create();
    reqDomain.on('error', function(err) {
        console.log(err.stack);
        res.statusCode = 500;
        res.end(err.message + '\n');
        reqDomain.dispose();
    });
    reqDomain.add(req);
    reqDomain.add(res);
    reqDomain.run(next);
});
  1. Use forever to start app.js: Forever acts as a daemon process for Node.js that can start, stop, and restart your app.
1
forever start app.js

Through these methods, you can improve the stability of Node.js services and prevent the entire service from crashing due to uncaught exceptions.