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');
});
Why is the second express
middleware still executed even though I don't call next in the error middleware and execute res.json()
?
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.