0
0
Node.jsframework~15 mins

Unhandled rejection handling in Node.js - Mini Project: Build & Apply

Choose your learning style9 modes available
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
Need a 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
Need a 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
Need a 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
Need a hint?

Simply leave failingPromise without any catch or then handlers.