Introduction
Error response formatting helps your app send clear and consistent messages when something goes wrong. It makes it easier for users and developers to understand the problem.
res.status(statusCode).json({ error: { message: 'Error message', code: 'ERROR_CODE' } })res.status(404).json({ error: { message: 'Not found', code: 'NOT_FOUND' } })
res.status(400).json({ error: { message: 'Invalid input', code: 'BAD_REQUEST' } })
res.status(500).json({ error: { message: 'Server error', code: 'INTERNAL_ERROR' } })
import express from 'express'; const app = express(); app.get('/user/:id', (req, res) => { const userId = req.params.id; if (!userId.match(/^\d+$/)) { return res.status(400).json({ error: { message: 'User ID must be a number', code: 'INVALID_ID' } }); } // Simulate user not found if (userId !== '123') { return res.status(404).json({ error: { message: 'User not found', code: 'USER_NOT_FOUND' } }); } res.json({ id: userId, name: 'Alice' }); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
res.status() in Node.js error handling?res.status()res.status(code) to set status, then json() to send JSON.res.status(404).json({ error: 'Not found' }) is valid syntax.app.use((err, req, res, next) => {
res.status(500).json({
message: err.message,
code: 'SERVER_ERROR'
});
});app.use((err, req, res) => {
res.status(400).json({ message: err.message });
});next, so Express won't recognize it as error handler.statusCode property. Otherwise, send a 500 status with a generic message. Which code snippet correctly implements this in Express?err.statusCode if present, else default to 500; similarly for message.res.status(status) and send JSON with code and message fields.Pass the test and this pattern moves unknown