1

In my express application when the error middleware is reached it still executes the second middleware function after res.json. The docs says that:

The methods on the response object (res) in the following table can send a response to the client, and terminate the request-response cycle. If none of these methods are called from a route handler, the client request will be left hanging.

Where res.json is one of the methods in the table which would terminate the request-response cycle. Also I don't call next in my express error middleware

router.use((err, req, res, next) => {
    res.json({
        success: false,
        message: 'fail: email already exists'
    });
});


//test still gets logged even though the express error middleware is executed
router.post('/', (req, res , next) => {
    console.log('test');

});

Question:

Why is the second express middleware still executed even though I don't call next in the error middleware and execute res.json()?

1 Answer 1

2

Per the documentation on error handling you must specify the error handling middleware last for it to work properly.

It is likely that by having that with an error signature that is is getting confused.

Sign up to request clarification or add additional context in comments.

2 Comments

so all the error handling middleware has to be defined at the end?
Yes. You have to always have the error handling be the last middleware in the chain. It's a bit of a goofy requirement I think, but that's the way it is.

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.