Bird
Raised Fist0
Node.jsframework~10 mins

Unhandled rejection handling in Node.js - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

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
Concept Flow - Unhandled rejection handling
Promise created
Promise rejected?
NoPromise resolved, normal flow
Yes
Is rejection handled?
YesHandle rejection with .catch() or try/catch
No
Node.js emits 'unhandledRejection' event
Optional process exit or logging
Program continues or stops
This flow shows how Node.js handles promises that reject without a catch handler, emitting an event if unhandled.
Execution Sample
Node.js
const p = Promise.reject(new Error('fail'));
// No catch handler

process.on('unhandledRejection', (reason) => {
  console.log('Unhandled rejection:', reason.message);
});
This code creates a rejected promise without a catch, triggering the unhandledRejection event.
Execution Table
StepActionPromise StateHandler Present?Event EmittedOutput
1Create rejected promiseRejectedNoNo
2No catch handler attachedRejectedNoNo
3Event loop checks for unhandled rejectionsRejectedNoYesunhandledRejection event emitted
4Event listener logs rejection reasonRejectedNoYesUnhandled rejection: fail
5Program continues or exits based on policyRejectedNoYes
💡 Unhandled rejection detected with no handler, event emitted and logged.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
pundefinedRejected Promise(Error: fail)Rejected Promise(Error: fail)Rejected Promise(Error: fail)Rejected Promise(Error: fail)
handlerAttachedfalsefalsefalsefalsefalse
eventEmittedfalsefalsefalsetruetrue
Key Moments - 3 Insights
Why does Node.js emit an 'unhandledRejection' event?
Because the promise was rejected but no catch handler was attached, as shown in execution_table step 3.
What happens if we add a .catch() handler after the rejection?
The rejection is handled, so the 'unhandledRejection' event is not emitted. This is because handlerAttached would be true, preventing event emission.
Does the program stop immediately after an unhandled rejection?
Not necessarily. Node.js emits the event and logs it, but the program continues unless explicitly exited, as shown in execution_table step 5.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, at which step is the 'unhandledRejection' event emitted?
AStep 1
BStep 3
CStep 5
DStep 2
💡 Hint
Check the 'Event Emitted' column in the execution_table rows.
According to variable_tracker, what is the value of 'handlerAttached' after step 2?
Atrue
Bundefined
Cfalse
Dnull
💡 Hint
Look at the 'handlerAttached' row and the 'After Step 2' column.
If a .catch() handler is added immediately after promise creation, how would the 'eventEmitted' variable change?
AIt would become false
BIt would remain true
CIt would become undefined
DIt would become null
💡 Hint
Refer to the explanation in key_moments about handler presence preventing event emission.
Concept Snapshot
Unhandled rejection handling in Node.js:
- When a Promise rejects without a catch, Node.js emits 'unhandledRejection'.
- Attach .catch() or use try/catch with async/await to handle rejections.
- Listen to 'unhandledRejection' on process to log or handle globally.
- Program continues unless explicitly exited.
- Helps avoid silent failures in async code.
Full Transcript
In Node.js, when a Promise is rejected but no catch handler is attached, the runtime emits an 'unhandledRejection' event. This event allows developers to detect and log errors that would otherwise be missed. The example code creates a rejected Promise without a catch handler, triggering this event. The execution table shows the promise state and event emission steps. Variables track the promise state, handler presence, and event emission. Key moments clarify why the event is emitted, what happens if a handler is added, and that the program does not stop immediately. The visual quiz tests understanding of when the event fires and variable states. This helps beginners see how unhandled rejections flow through Node.js and how to handle them properly.

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

  1. Step 1: Understand what unhandled rejections are

    Unhandled rejections happen when a promise fails but no .catch() or try-catch handles the error.
  2. 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.
  3. Final Answer:

    To catch errors from promises that were not handled anywhere else -> Option A
  4. Quick Check:

    Unhandled promise errors = process.on('unhandledRejection') [OK]
Hint: Unhandled promise errors are caught by process.on('unhandledRejection') [OK]
Common Mistakes:
  • Confusing unhandledRejection with synchronous try-catch
  • Thinking it restarts the server automatically
  • Assuming it logs successful promises
2. Which of the following is the correct syntax to listen for unhandled promise rejections in Node.js?
easy
A. process.on('unhandledRejection', handlerFunction)
B. process.catch('unhandledRejection', handlerFunction)
C. process.listen('unhandledRejection', handlerFunction)
D. process.handle('unhandledRejection', handlerFunction)

Solution

  1. Step 1: Recall Node.js event listening syntax

    Node.js uses process.on(eventName, callback) to listen to events.
  2. Step 2: Match the event name and method

    The event for unhandled promise rejections is 'unhandledRejection', so the correct syntax is process.on('unhandledRejection', handlerFunction).
  3. Final Answer:

    process.on('unhandledRejection', handlerFunction) -> Option A
  4. Quick Check:

    Event listening in Node.js = process.on() [OK]
Hint: Use process.on('unhandledRejection', handler) to catch promise errors [OK]
Common Mistakes:
  • Using process.catch instead of process.on
  • Using process.listen or process.handle which don't exist
  • Mixing event name spelling
3. Consider this Node.js code snippet:
process.on('unhandledRejection', (reason) => {
  console.log('Error:', reason.message);
});

Promise.reject(new Error('Failed promise'));

What will be printed to the console?
medium
A. No output, program crashes silently
B. Error: Failed promise
C. Error: undefined
D. Unhandled promise rejection

Solution

  1. Step 1: Understand the unhandledRejection event handler

    The handler logs the error message from the rejection reason.
  2. Step 2: Analyze the rejected promise

    The promise rejects with new Error('Failed promise'), so reason.message is 'Failed promise'.
  3. Final Answer:

    Error: Failed promise -> Option B
  4. Quick Check:

    Rejected error message logged = 'Error: Failed promise' [OK]
Hint: Unhandled rejection logs error.message from rejected Error object [OK]
Common Mistakes:
  • Expecting no output or silent crash
  • Confusing reason.message with undefined
  • Thinking the event logs generic text
4. You wrote this code to catch unhandled promise rejections:
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?
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

  1. Step 1: Check the rejection reason type

    The promise rejects with a string 'Oops!', not an Error object.
  2. 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.
  3. Final Answer:

    The rejection reason is a string, not an Error object, so error.message is undefined -> Option D
  4. 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); });
C. process.on('unhandledRejection', (reason) => { console.error('Unhandled rejection:', reason); server.close(() => process.exit(1)); });
D. process.on('unhandledRejection', async (reason) => { await server.close(); console.log('Server closed'); });

Solution

  1. Step 1: Understand graceful shutdown

    Graceful shutdown means closing server connections before exiting the process.
  2. 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.
  3. 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.
  4. Final Answer:

    process.on('unhandledRejection', (reason) => { console.error('Unhandled rejection:', reason); server.close(() => process.exit(1)); }); -> Option C
  5. Quick Check:

    Graceful shutdown = server.close() then exit [OK]
Hint: Close server before exit to shutdown gracefully [OK]
Common Mistakes:
  • Exiting process immediately without closing server
  • Not calling process.exit after closing server
  • Logging without shutting down server