Imagine you build a web app with Express. What is the main reason to add error handling middleware?
Think about what happens if an error occurs but is not caught.
Error handling middleware in Express catches errors during request processing. Without it, the server might crash or send confusing responses. Proper error handling keeps the app stable and user-friendly.
Consider this Express route:
app.get('/data', (req, res) => { throw new Error('Oops!'); });What will the server do if no error handling middleware is added?
app.get('/data', (req, res) => { throw new Error('Oops!'); });
Think about what happens when an exception is not caught in Node.js.
Without error handling middleware, throwing an error in a route causes the server to crash or send a default error response, which is not user-friendly and can stop the app.
Which of these is the correct way to define error handling middleware in Express?
Error middleware must have four parameters: err, req, res, next.
Express error handling middleware requires four parameters. Option A correctly uses (err, req, res, next). Other options miss parameters or use wrong methods.
Look at this code snippet:
app.use((err, req, res, next) => { res.status(500).send('Caught error'); });
app.use((req, res, next) => { throw new Error('Fail'); });Why does the error handler not catch the error?
app.use((err, req, res, next) => { res.status(500).send('Caught error'); });
app.use((req, res, next) => { throw new Error('Fail'); });Order of middleware matters in Express.
Express executes middleware in the order defined. Error-handling middleware only catches errors thrown in or passed via next(err) from previous middleware. Here, the error handler is before the throwing middleware, so when the error is thrown, Express looks for error middleware after it but finds none, falling back to the default error handler.
Given this Express code:
app.get('/test', (req, res, next) => {
next(new Error('Test error'));
});
app.use((err, req, res, next) => {
res.status(400).json({ message: err.message });
});What will the client receive when requesting /test?
app.get('/test', (req, res, next) => { next(new Error('Test error')); }); app.use((err, req, res, next) => { res.status(400).json({ message: err.message }); });
What does calling next(error) do in Express?
Calling next(error) passes the error to the error handling middleware. The middleware sets status 400 and sends JSON with the error message. So the client gets status 400 and the JSON body.