Performance: Error response formatting
This affects the speed of sending error responses and the user's perception of app responsiveness during failures.
app.use((err, req, res, next) => {
res.status(500).json({ error: 'Internal Server Error' });
});app.use((err, req, res, next) => {
res.status(500).send(`<html><body><h1>Error</h1><pre>${err.stack}</pre></body></html>`);
});| Pattern | Response Size | Parsing Time | Rendering Delay | Verdict |
|---|---|---|---|---|
| Full HTML error with stack trace | Large (5-10kb+) | High | High (blocks rendering) | [X] Bad |
| Minimal JSON error message | Small (<1kb) | Low | Low (fast render) | [OK] Good |
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