Unhandled promise rejections happen when a promise fails but no code catches the error. Handling them helps keep your program stable and avoid crashes.
Unhandled rejection handling in Node.js
Start learning this pattern below
Jump into concepts and practice - no test required
process.on('unhandledRejection', (reason, promise) => {
// handle the error here
});This listens for any promise rejection that was not caught.
The reason is the error or value that caused the rejection.
process.on('unhandledRejection', (reason, promise) => { console.log('Unhandled rejection:', reason); });
process.on('unhandledRejection', (reason, promise) => { // Exit the process after logging console.error('Error:', reason); process.exit(1); });
This program listens for unhandled promise rejections and logs the error message. The promise rejects without a catch, so the handler runs.
process.on('unhandledRejection', (reason, promise) => { console.log('Caught unhandled rejection:', reason.message); }); // Create a promise that rejects but has no catch new Promise((resolve, reject) => { reject(new Error('Oops!')); });
Always try to handle promise errors with .catch() or try/catch in async functions.
Use unhandled rejection handling as a safety net, not a replacement for proper error handling.
In Node.js 15+, unhandled rejections may cause the process to exit by default, so handling them is important.
Unhandled rejection handling catches errors from promises that no one caught.
It helps keep your app stable and lets you log or clean up on errors.
Use process.on('unhandledRejection') to listen and respond to these errors.
Practice
process.on('unhandledRejection') in a Node.js application?Solution
Step 1: Understand what unhandled rejections are
Unhandled rejections happen when a promise fails but no .catch() or try-catch handles the error.Step 2: Role of process.on('unhandledRejection')
This event listener catches those unhandled promise errors so you can log or clean up before the app crashes.Final Answer:
To catch errors from promises that were not handled anywhere else -> Option AQuick Check:
Unhandled promise errors = process.on('unhandledRejection') [OK]
- Confusing unhandledRejection with synchronous try-catch
- Thinking it restarts the server automatically
- Assuming it logs successful promises
Solution
Step 1: Recall Node.js event listening syntax
Node.js usesprocess.on(eventName, callback)to listen to events.Step 2: Match the event name and method
The event for unhandled promise rejections is 'unhandledRejection', so the correct syntax isprocess.on('unhandledRejection', handlerFunction).Final Answer:
process.on('unhandledRejection', handlerFunction) -> Option AQuick Check:
Event listening in Node.js = process.on() [OK]
- Using process.catch instead of process.on
- Using process.listen or process.handle which don't exist
- Mixing event name spelling
process.on('unhandledRejection', (reason) => {
console.log('Error:', reason.message);
});
Promise.reject(new Error('Failed promise'));What will be printed to the console?
Solution
Step 1: Understand the unhandledRejection event handler
The handler logs the error message from the rejection reason.Step 2: Analyze the rejected promise
The promise rejects withnew Error('Failed promise'), so reason.message is 'Failed promise'.Final Answer:
Error: Failed promise -> Option BQuick Check:
Rejected error message logged = 'Error: Failed promise' [OK]
- Expecting no output or silent crash
- Confusing reason.message with undefined
- Thinking the event logs generic text
process.on('unhandledRejection', (error) => {
console.log('Caught:', error);
});
Promise.reject('Oops!');But the console shows
Caught: Oops! instead of an error message. What is the issue?Solution
Step 1: Check the rejection reason type
The promise rejects with a string 'Oops!', not an Error object.Step 2: Understand how the handler logs the error
The handler logs the whole error variable, which is the string 'Oops!', so it prints exactly that.Final Answer:
The rejection reason is a string, not an Error object, so error.message is undefined -> Option DQuick Check:
Rejection reason type affects error.message presence [OK]
- Using wrong event name 'unhandledRejections'
- Thinking async handler is required
- Believing try-catch catches unhandled rejections
Solution
Step 1: Understand graceful shutdown
Graceful shutdown means closing server connections before exiting the process.Step 2: Analyze each option's shutdown approach
process.on('unhandledRejection', (reason) => { console.error('Unhandled rejection:', reason); server.close(() => process.exit(1)); }); logs the error, then callsserver.close()with a callback to exit after closing. This is correct.Step 3: Identify why others are incorrect
process.on('unhandledRejection', (reason) => { console.error('Unhandled rejection:', reason); process.exit(1); }); exits immediately without closing server; C only logs without shutdown; D awaits server.close but does not exit process.Final Answer:
process.on('unhandledRejection', (reason) => { console.error('Unhandled rejection:', reason); server.close(() => process.exit(1)); }); -> Option CQuick Check:
Graceful shutdown = server.close() then exit [OK]
- Exiting process immediately without closing server
- Not calling process.exit after closing server
- Logging without shutting down server
