Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Handling Unhandled Promise Rejections in Node.js
📖 Scenario: You are building a simple Node.js script that uses promises to simulate asynchronous tasks. Sometimes, promises might reject without proper handling, causing unhandled rejection warnings or crashes.To make your application more reliable, you want to catch and handle any unhandled promise rejections globally.
🎯 Goal: Create a Node.js script that defines a promise which rejects without a catch, then add a global handler for unhandled promise rejections to log a friendly message.
📋 What You'll Learn
Create a promise that rejects with the message 'Task failed!'
Add a global event listener for 'unhandledRejection' on the process object
Log the rejection reason with a clear message inside the event listener
Trigger the unhandled rejection by not catching the promise rejection
💡 Why This Matters
🌍 Real World
In real Node.js applications, unhandled promise rejections can cause crashes or silent failures. Handling them globally helps keep the app stable and easier to debug.
💼 Career
Understanding unhandled rejection handling is important for backend developers to write robust asynchronous code and maintain production server stability.
Progress0 / 4 steps
1
Create a promise that rejects
Create a constant called failingPromise that is a new Promise which immediately rejects with the string 'Task failed!'.
Node.js
Hint
Use new Promise((resolve, reject) => { reject('Task failed!'); }) to create the promise.
2
Add a global unhandledRejection event listener
Add a listener on the process object for the 'unhandledRejection' event. The listener should be a function with parameters reason and promise.
Node.js
Hint
Use process.on('unhandledRejection', (reason, promise) => { ... }) to listen globally.
3
Log the rejection reason inside the event listener
Inside the unhandledRejection event listener, add a console.log statement that outputs the string 'Unhandled rejection:' followed by the reason parameter.
Node.js
Hint
Use console.log('Unhandled rejection:', reason) inside the listener function.
4
Trigger the unhandled rejection by not catching the promise
Do not add any catch or then handlers to failingPromise. This will cause the rejection to be unhandled and trigger the global listener.
Node.js
Hint
Simply leave failingPromise without any catch or then handlers.
Practice
(1/5)
1. What is the main purpose of using process.on('unhandledRejection') in a Node.js application?
easy
A. To catch errors from promises that were not handled anywhere else
B. To handle synchronous errors in try-catch blocks
C. To restart the Node.js server automatically
D. To log all successful promise resolutions
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 A
But the console shows Caught: Oops! instead of an error message. What is the issue?
medium
A. The handler function must be async to catch rejections
B. The event name should be 'unhandledRejections' (plural)
C. You must use try-catch instead of process.on for promises
D. The rejection reason is a string, not an Error object, so error.message is undefined
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 D
Quick Check:
Rejection reason type affects error.message presence [OK]
Hint: Rejection reason can be any type; strings have no .message [OK]
Common Mistakes:
Using wrong event name 'unhandledRejections'
Thinking async handler is required
Believing try-catch catches unhandled rejections
5. You want to log unhandled promise rejections and then gracefully shut down your Node.js server. Which code snippet correctly implements this behavior?
hard
A. process.on('unhandledRejection', (reason) => {
console.error('Unhandled rejection:', reason);
process.exit(1);
});
B. process.on('unhandledRejection', (reason) => {
console.log('Handled rejection:', reason.message);
});
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 calls server.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.