Willem van der Veen
Willem van der Veen

Reputation: 36580

Express4 error middleware sequence

Came accros a sequence of code execution which I found unusual here is the code:

server.js

const Actions_Single_PVC = require('./routes/Actions_single_PVC.js');

app.use('/Actions_single_PVC', Actions_Single_PVC);

app.use((err, req, res, next) => {

    console.log('invalid token');

});

Actions_single_PVC.js

router.post('/', asyncMW(async (req, res, next) => {

throw new Error();

}));

router.use((err, req, res, next) => {
  console.log('error');
}

And in case you have never seen this construction before here is asyncMW:

const asyncMiddleware = fn =>
  (req, res, next) => {
    Promise.resolve(fn(req, res, next))
      .catch(next);
  };

  module.exports = asyncMiddleware;

What I didn't understand was that when an error is thrown (I reproduced it here with throw new Error();) that the error handling middleware in the server.js file is executed. I expected that the error handling middleware of the Actions_single_PVC.js would get executed.

Question:

Why is the error middlware in server.js executed and not the error middlware in Actions_single_PVC.js?

Upvotes: 1

Views: 59

Answers (1)

Farhan Tahir
Farhan Tahir

Reputation: 2134

It is because the following code applies middleware to only request with base path matching Actions_single_PVC.

app.use('/Actions_single_PVC', Actions_Single_PVC);

Whereas following code is apply middleware to all global requests.

app.use((err, req, res, next) => {

    console.log('invalid token');

});

If you'll hit the url /Actions_single_PVC then the middlewares in Actions_single_PVC will get hit.

Upvotes: 4

Related Questions