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 Middleware in Context

Andrés Muñoz
PLUS
Andrés Muñoz
Courses Plus Student 4,031 Points

Why the catch error 404 on line 24 is not fired ?

I dont get why the middleware that catch the error is not fired like in the previous videos ?

1 Answer

When Express sends a response back to the client, all other middleware or routes AFTER the response wont be reached.

//1
app.use((req, res, next) => {
    const {body: {number}} = req;
    const num = parseFloat(number);
    const result = num * 2;
    req.doubled = result;
    next();
});

//2
app.get('/', (req, res, next) => {
  res.render('index');
});

//3
app.post('/', ({doubled}, res, next) => {
  res.render('index', {doubled});
});

//4
app.use((req, res, next) => {
  const err = new Error('Not Found');
  err.status = 404;
  next(err);
});

In the video we only reach the GET / and POST / routes which successfully sends a response back to the client with res.render method. Therefore, we never reach number 4.

But if we were to make a request to say GET /bro we would enter number 1 call its next method, skip number 2 and 3 (no response is sent back to client) and finally reach number 4 to send an error because a response wasn't found.