Express.js
Beginner
1 min read
Async Error Handling Patterns
Example
// Pattern 1 – manual try/catch (always safe)
app.get('/a', async (req, res, next) => {
try {
const data = await fetchData();
res.json(data);
} catch (err) {
next(err); // forward to error handler
}
});
// Pattern 2 – asyncHandler wrapper (DRY)
const asyncHandler = fn => (req, res, next) =>
Promise.resolve(fn(req, res, next)).catch(next);
app.get('/b', asyncHandler(async (req, res) => {
const data = await fetchData(); // any throw is caught
res.json(data);
}));
// Pattern 3 – express-async-errors package (global patch)
require('express-async-errors'); // patch Express once
app.get('/c', async (req, res) => {
const data = await fetchData(); // no wrapper needed
res.json(data);
});
// Process-level safety net
process.on('unhandledRejection', (reason) => {
console.error('Unhandled Rejection:', reason);
process.exit(1); // let PM2/Kubernetes restart
});
process.on('uncaughtException', (err) => {
console.error('Uncaught Exception:', err);
process.exit(1);
});
Related Resources
Express.js Reference
Complete tag & property list
Express.js How-To Guides
Step-by-step practical guides
Express.js Exercises
Practice what you've learned
More in Express.js