gotchajavascriptnodejsMajorpending
Gotcha: Node.js unhandled promise rejections crash the process
Viewed 0 times
unhandled-rejectionpromisecrashcatchasync-handler
Error Messages
Problem
Starting from Node.js 15, unhandled promise rejections terminate the process by default. Missing a .catch() or try/catch around await crashes your server.
Solution
Handle all promise rejections:
// BAD - unhandled rejection crashes process:
async function fetchData() {
const data = await fetch('/api/data'); // If this throws, crash!
return data.json();
}
fetchData(); // No .catch(), no try/catch!
// GOOD - handle errors:
async function fetchData() {
try {
const data = await fetch('/api/data');
return data.json();
} catch (error) {
console.error('Fetch failed:', error);
return null;
}
}
// GOOD - .catch() on promise chain:
fetchData().catch(console.error);
// Global safety net (DON'T rely on this, fix the source):
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection:', reason);
// Log and monitor, but fix the actual missing handler
});
// Express.js gotcha - async route handlers:
// BAD: app.get('/api', async (req, res) => { ... }) // Unhandled if throws
// GOOD: Use express-async-errors or wrap:
const asyncHandler = fn => (req, res, next) =>
Promise.resolve(fn(req, res, next)).catch(next);
app.get('/api', asyncHandler(async (req, res) => { ... }));
// BAD - unhandled rejection crashes process:
async function fetchData() {
const data = await fetch('/api/data'); // If this throws, crash!
return data.json();
}
fetchData(); // No .catch(), no try/catch!
// GOOD - handle errors:
async function fetchData() {
try {
const data = await fetch('/api/data');
return data.json();
} catch (error) {
console.error('Fetch failed:', error);
return null;
}
}
// GOOD - .catch() on promise chain:
fetchData().catch(console.error);
// Global safety net (DON'T rely on this, fix the source):
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection:', reason);
// Log and monitor, but fix the actual missing handler
});
// Express.js gotcha - async route handlers:
// BAD: app.get('/api', async (req, res) => { ... }) // Unhandled if throws
// GOOD: Use express-async-errors or wrap:
const asyncHandler = fn => (req, res, next) =>
Promise.resolve(fn(req, res, next)).catch(next);
app.get('/api', asyncHandler(async (req, res) => { ... }));
Revisions (0)
No revisions yet.