What if your app could catch hidden promise errors before they break everything?
Why Unhandled rejection handling in Node.js? - Purpose & Use Cases
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine you write a Node.js app that calls many asynchronous functions returning promises. Sometimes, a promise fails but you forget to catch the error.
Your app crashes unexpectedly or behaves strangely without clear clues.
Manually tracking every promise rejection is hard and easy to miss.
Unhandled rejections cause crashes or silent bugs that are tough to debug.
This leads to poor user experience and unreliable apps.
Unhandled rejection handling lets Node.js catch any promise errors you forgot to handle.
This gives you a chance to log errors, clean up, or recover gracefully.
It makes your app more stable and easier to maintain.
someAsyncFunction().then(result => { /* use result */ }); // no catchprocess.on('unhandledRejection', (reason, promise) => { console.error('Unhandled Rejection at:', promise, 'reason:', reason); });
You can build robust Node.js apps that handle unexpected promise errors without crashing.
A web server that logs unhandled promise errors instead of crashing, keeping the site online and alerting developers.
Missing promise error handling causes crashes and bugs.
Node.js unhandled rejection event catches forgotten errors.
This improves app stability and debugging.
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
