reggie
reggie

Reputation: 3674

Express next() header error

In a route I have this:

            if (elements.length <= 0) {
                var msg = 'no elements found';
                console.error(msg);
                var err = new Error('Not found');
                err.status = 404;
                err.message = msg;
                next(err);
            }

            console.log('Found ' + elements.length + ' elements');
            res.setHeader('Content-Type', 'application/json'); /*error*/
            res.status(200).json(elements);
            res.end();

The error handler that is defined last in app.js:

// development error handler
app.use(function(err, req, res, next) {
    res.type('application/json');
    res.status(err.status || 500);
    res.json({
        message: err.message,
        error: err
    });
});

I see that the error is sent as response in json. But I get this error on the line marked with /error/:

Can't set headers after they are sent.

Why is express returning from the error handler? I can see that it is continuing the execution of the route (from the console.log) Why is it continuing execution of the route?

Upvotes: 1

Views: 91

Answers (1)

Viktor Kireev
Viktor Kireev

Reputation: 1240

Inside if statement correct:

return next(err);

Upvotes: 2

Related Questions