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 trial

JavaScript REST APIs with Express Refactoring and Modularizing a REST API Writing a Global Error Handler

Luis Walderdorff
.a{fill-rule:evenodd;}techdegree seal-36
Luis Walderdorff
Full Stack JavaScript Techdegree Graduate 27,070 Points

How does the code know to use the global error handler, when you enter next(err)?

Couldn't it be, that there are multiple app.use handlers which end with next(something)? Does it mean every next() needs a unique variable? And next(err) gets created later than the delete request we enter it at, so when the code looks through all routes from top to bottom and stops at one that fits, shouldn't that mean that at the delete route, next(err) hasn't been created yet?

1 Answer

in express, error handler functions are the only functions with 4 parameters (with the error object being the first parameter).

When next() is run, if it contains an error object, it will run the first error handler function it can find that it can find from that point forward. If next() does not contain an error object, it will run the next middleware function that is not an error handler.