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


It seems like error reporting/handling is done differently in Node.js+Express.js applications compared to other frameworks. Am I correct in understanding that it works as follows?

A) Detect errors by receiving them as parameters to your callback functions. For example:

doSomethingAndRunCallback(function(err) { 
    if(err) { … }

B) Report errors in MIDDLEWARE by calling next(err). Example:

handleRequest(req, res, next) {
    // An error occurs…

C) Report errors in ROUTES by throwing the error. Example:

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

D) Handle errors by configuring your own error handler via app.error() or use the generic Connect error handler. Example:

app.error(function(err, req, res, next) {
    res.send('Fail Whale, yo.');

Are these four principles the basis for all error handling/reporting in Node.js+Express.js applications?

5/4/2015 10:26:30 AM

Accepted Answer

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

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


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.

5/4/2015 10:28:32 AM

People at Joyent have published a really insightful best-practices document on this. A must-read article for any Node.js developer.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow