Introduction
We format error responses to clearly tell the user or developer what went wrong in a simple and consistent way.
res.status(statusCode).json({ error: 'Error message here' })res.status(404).json({ error: 'Page not found' })
res.status(400).json({ error: 'Invalid input data' })
res.status(500).json({ error: 'Server error, please try later' })
import express from 'express'; const app = express(); app.use(express.json()); app.get('/item/:id', (req, res) => { const id = req.params.id; if (isNaN(id)) { return res.status(400).json({ error: 'ID must be a number' }); } if (id !== '1') { return res.status(404).json({ error: 'Item not found' }); } res.json({ id: 1, name: 'Sample Item' }); }); app.use((err, req, res, next) => { console.error(err); res.status(500).json({ error: 'Internal server error' }); }); app.listen(3000, () => console.log('Server running on port 3000'));
res.status() in Express error handling?res.status()res.status() only sets the status code, which is essential for error handling.res.status(code) sets the status, and res.json(object) sends JSON data.status(404) and json({ error: 'Not found' }). Others misuse method order or types.app.get('/data', (req, res) => {
if (!req.query.id) {
return res.status(400).json({ error: 'ID is required' });
}
res.json({ id: req.query.id });
});req.query.id is missing, the code returns a 400 status with JSON error message.res.status(400).json({ error: 'ID is required' }), so status is 400 and body contains the error message.app.use((err, req, res, next) => {
res.json({ error: err.message });
res.status(500);
});res.json() sends the response immediately. Setting status after sending has no effect.res.status(500).json(...).{ error: 'Invalid input', fields: ['name', 'email'] }. Which Express code snippet correctly formats this error response?res.status(422) to set the correct HTTP status code before sending JSON.error and fields keys as specified.Pass the test and this pattern moves unknown