Performance: Error-handling middleware
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 |
const express = require('express');
const app = express();
app.get('/', (req, res) => {
throw new Error('Oops!');
});
app.use((err, req, res, next) => {
res.status(500).send('Error caught: ' + err.message);
});
app.listen(3000);app.use((req, res, next, err) => {
res.status(500).send('Error: ' + err.message);
});A) app.use((err, req, res, next) => {
console.log(err.message);
next(err);
});
B) app.use((req, res, next, err) => {
console.log(err.message);
next();
});
C) app.use((err, req, res) => {
console.log(err.message);
next(err);
});
D) app.use((err, req, res, next) => {
console.log(err.message);
res.send('Error logged');
});Pass the test and this pattern moves unknown