1

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?

1 Answer 1

2

Inside if statement correct:

return next(err);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.