Untitled Lesson
Skill Matrix
UNLOCK NODES BY LEARNING NEW TAGS.
A.D.A. Interface
Adaptive Didactic Assistant

Pascual Vila
Frontend Instructor // Code Syllabus
The Error //
An unhandled Promise rejection inside an async route silently crashes the process
// Wrong: unhandled rejection can crash the whole process
app.get('/user/:id', async (req, res) => {
const user = await db.findById(req.params.id); // throws if DB is down
res.json(user);
});
// Correct: forward to the global error handler
app.get('/user/:id', async (req, res, next) => {
try {
const user = await db.findById(req.params.id);
res.json(user);
} catch (err) {
next(err);
}
});The Solution //
In modern Node versions, an unhandled promise rejection terminates the process by default (process.on('unhandledRejection') no longer just warns). An async controller that throws without a surrounding try/catch ā or without forwarding to next(err) ā can take the entire server down on a single bad request. Wrap every async handler (or use a wrapper util) so rejections always reach next(err) and the global error middleware.
The Error //
The global error-handling middleware is defined before other routes/middleware, so it never catches anything
// Wrong: error handler registered first
app.use((err, req, res, next) => { /* ... */ });
app.use('/users', userRoutes);
// Correct: error handler registered LAST
app.use('/users', userRoutes);
app.use((err, req, res, next) => {
res.status(err.statusCode || 500).json({ status: 'error', message: err.message });
});The Solution //
Express only recognizes a four-parameter function as error middleware, and it only receives control when something ahead of it calls next(err). If it's registered before your routes instead of after all of them (as the very last app.use()), errors thrown by later routes never reach it at all.