myNewAccount
myNewAccount

Reputation: 640

Why might Express error handling middleware not receive req.session?

Environment: node.js, Express, express-session package.

Background: I was testing an Express error handler and I got an error that I wasn't expecting.

The following simplified route throws an error.

TypeError: Cannot read property 'userValues' of undefined

exports.errorHandler = wrapAsync(async function(error, req, res, next) {

    let loggedIn = req.session.userValues ? true : false;

    res.render('error', { loggedIn });
});

However when I remove the error parameter it works without an error as I had anticipated.

exports.errorHandler = wrapAsync(async function(req, res, next) {

    let loggedIn = req.session.userValues ? true : false;

    res.render('error', { loggedIn });
});

Why might this be?

The basic pattern in the second example works in several dozen routes that don't include the error parameter.

Upvotes: 0

Views: 388

Answers (1)

user9201277
user9201277

Reputation:

You could use something like this. And it will only get executed whenever there is an ERROR 500 unless you passed the ERROR 404 to this one using next() function, if you handled all the errors correctly you should be able to make an ERROR 500 and this should be able to catch that ERROR.

const errorHandler = require("./your-file");

...
... every other route even error 404 handler
...

app.use(errorHandler);

What do I mean by using next() for ERROR 404

If you have used express-generator then you should already have this piece of code:

// catch 404 and forward to error handle
app.use((req, res, next) => {
    next('not found');
});

The end file should looks something like this now if you use this approach:

...
... all previous routes
...

// catch 404 and forward to error handle
app.use((req, res, next) => {
    next('not found');
});

// handle all other error
app.use(errorHandler);

Hope this helps

Upvotes: 1

Related Questions