Take the 2-minute tour ×

It seems like error reporting/handling is done differently in NodeJS+Express apps 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:

    // 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:

    res.send('Fail Whale, yo.');

Are these four principles the basis for all error handling/reporting in NodeJS+Express apps? Thanks!

share|improve this question

1 Answer 1

up vote 138 down vote accepted

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

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

C) is bad practice if you ask me.

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


  // 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.

share|improve this answer
Thanks! For anyone who might come across this in the future, it looks like the order of params for "method e" is actually err, req, res, next (instead of req, res, next, err). –  Clint Harris Aug 22 '11 at 22:30
So this looks great, but a problem I'm seeing is that some errors never make their way to the error handlers you describe, and can only be caught by a process.on('uncaughtException', fn) handler. The conventional wisdom is to let that happen and rely on Forever or the like to restart the app, but if you do that, how do you return a friendly error page? –  Paul Apr 18 '12 at 17:29
@chovy Also, just an fyi. The error handler has to be given to the app after the thrown/next'd error. If it is before, it will not catch the error. –  Lee Olayvar Dec 7 '12 at 21:25
next(err) is essentially Express's version of throwing an error, you have to explicitly call it within your own middleware though –  qodeninja Jan 28 at 20:25
@qodeninja That method is considered a best practice in Express. –  David Oliveros Feb 11 at 20:03

Your Answer


