Performance: Error-handling middleware
MEDIUM IMPACT
This affects server response time and user experience by managing errors efficiently without blocking the event loop.
app.get('/data', (req, res, next) => { try { const data = getDataSync(); if (!data) { throw new Error('Data not found'); } res.send(data); } catch (err) { next(err); } }); app.use((err, req, res, next) => { res.status(500).send({ error: err.message }); });
app.get('/data', (req, res) => { const data = getDataSync(); if (!data) { throw new Error('Data not found'); } res.send(data); });
| Pattern | Event Loop Blocking | Error Handling | Server Stability | Verdict |
|---|---|---|---|---|
| Throw error directly in route | Blocks event loop on error | No centralized handling | Crashes server | [X] Bad |
| Use try-catch and next(err) in sync routes | Non-blocking | Centralized handling | Stable server | [OK] Good |
| Throw error in async route without next | Uncaught promise rejection | No handling | Potential memory leaks | [X] Bad |
| Use async try-catch with next(err) | Non-blocking | Centralized handling | Stable server | [OK] Good |