Error handling principles for Node.js + Express.js applications?

Error handling in Node.js is generally of the format A). Most callbacks return an error object as the first argument or null.

Express.js uses middleware and the middleware syntax uses B) and E) (mentioned below).

C) is bad practice if you ask me.

app.get('/home', function(req, res) {
    // An error occurs
    throw err;
});

You can easily rewrite the above as

app.get('/home', function(req, res, next) {
    // An error occurs
    next(err);
});

Middleware syntax is valid in a get request.

As for D)

(07:26:37 PM) tjholowaychuk: app.error is removed in 3.x

TJ just confirmed that app.error is deprecated in favor of E

E)

app.use(function(err, req, res, next) {
  // Only handle `next(err)` calls
});

Any middleware that has a length of 4 (4 arguments) is considered error middleware. When one calls next(err) connect goes and calls error-based middleware.

Leave a Comment