skip to Main Content

Why the execution reaches to the global error handler and the value of err is 404 as im sending the res from /test route the req-res cycle should be ended, its not throwing error in response but it logs 404 to console.

app.get('/test', (req, res, next) => {
  console.log('mw 1');
  res.send('hello');
});

// if none of the above routes matched
app.all('*', (req, res, next) => {
  next(404, `${req.originalUrl} not found`);
});

// Global error Handling
app.use((err, req, res, next) => {
  console.log('global error handler: ', err);
  res.status(500).json({
    status: '❌ error',
    message: err.message || 'Internal Server Error',
  });
});

Output:
mw 1
global error handler: 404

2

Answers


  1. I would guess that you’re seeing two separate incoming requests, one from the page you requested and then one the browser added one for /favicon.ico.

    Modify your error handler to output the request path like this:

    app.use((err, req, res, next) => {
      console.log(`global error on ${req.originalUrl}`);
      console.log('global error handler: ', err);
      res.status(500).json({
        status: '❌ error',
        message: err.message || 'Internal Server Error',
      });
    });
    

    To output the URL associated with the error.


    Or, just add this middleware as the very first request handler:

    app.use((req, res, next) => {
        console.log(`incoming request: ${req.originalUrl}`);
        next();
    });
    

    So, you can see every single incoming request.


    Also, note that next() takes zero or one argument. It doesn’t take two arguments like you’re doing. If you want to pass multiple values, then the argument to next can be an object with multiple properties (often an Error object).

    Login or Signup to reply.
  2. As in the middleware to handle all the undefined routes you are passing two values to the next and the first value is 404.

     next(404, `${req.originalUrl} not found`);
    

    so that you are recieving the 404 in every request. next accepts only one value. If next is called without any argument then the next middleware in the stack is called orhtewise it is handled by the global error handling middlware.

    Try modifying this:

    // if none of the above routes matched
    app.all('*', (req, res, next) => {
      const err = {
        statusCode: 404, 
        message: `${req.originalUrl} not found`
      }
    
      next(err);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search