0

I'm using Node with Express.js to write a back-end for a project I'm working on.

next() functions are used in middleware to move to the next piece in the middleware chain, and finally onto the app.VERB() function. Where and how (further down the line) do I access this variable?

Example code:

app.use(function (req, res, next) {

    User.findOne({
            'email': emailValue
        }, function (err, foundUser) {

            if (err) return next(err); 

            // Else do something
        }
    }); 
});

What has access to the err value passed to next()?

Alex
  • 8,353
  • 9
  • 45
  • 56
  • 1
    Does this help you ? http://stackoverflow.com/questions/18875292/passing-variables-to-the-next-middleware-using-next-in-expressjs –  Dec 04 '13 at 12:48
  • It's useful but doesn't answer the `next(var)` question. It's something I could use, but this seems to be built in functionality. I keep seeing `next(err)`. What has access to that variable? – Alex Dec 04 '13 at 12:55
  • If there's an error, the middleware stops processing. That's how you'd signal an error. It's not how you pass values. – WiredPrairie Dec 04 '13 at 13:38
  • As @StefanMoraru linked, a way to pass values along is to store them in the `req` parameter. – WiredPrairie Dec 04 '13 at 13:40

1 Answers1

2

When you pass an error parameter into next, Express invokes whatever error middleware handler you've installed. The error middleware function has four arguments, so you'd install your own handler as:

app.use(function(err, req, res, next) {
    // handle the err from a previous middleware's next(err) call
});

You'd typically add this at the end of your middleware chain so that it handles all other middlewares' errors.

See here for the Express documentation on this.

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • Would that also mean `app.get('/wherever', function (err, req, res, next) {...});` would work? – Alex Dec 04 '13 at 14:20
  • Okay. So what I was missing was this was purely for errors. I struggled to find anything on the Express site. Thanks for your help. – Alex Dec 04 '13 at 14:35
  • 1
    @Alexcoady Glad it helped. I added a link the Express docs on this to the answer. – JohnnyHK Dec 04 '13 at 14:44