Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialMatthew Olivares
4,181 PointsWhy does the 1st anon func. "next(err)" skip the 2nd anon. function in the "vote-:dir" handler to the error handler?
In the "/vote-:dir" handler, the "if" block creates an error with a 404 status for any request other than "up" or "down".
It is then passed through the next() function as such: next(err). However there is 2nd anonymous function after this that accepts (req, res). This anonymous function never calls next();
My understanding was that next() calls the next available middleware function sequentially.
But the variable "err" seems to bypass the 2nd anonymous function AND the main 404 catcher in "app.js" and moves directly to the error handler in "app.js" file.
What is going on? Does the 2nd anonymous function see that the variable passed into it's "req" parameter is an "Error" object and skip to the next available middleware function with 4 parameters (if it exists)?
1 Answer
Seth Kroger
56,413 PointsIt's not entirely true that "next() calls the next available middleware function sequentially". If next is called without an argument that is true but not if called with an argument. If next is called with an error as an argument, next(err)
it will skip all the remaining regular middleware and execute the first 4-argument (i.e. error handling) middleware.
Matthew Olivares
4,181 PointsMatthew Olivares
4,181 PointsThanks so much!