Handling uncaught exceptions helps keep your Node.js app running smoothly by catching errors that were not handled anywhere else.
Handling uncaught exceptions in Node.js
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Node.js
process.on('uncaughtException', (error) => {
// handle the error here
});Use
process.on('uncaughtException') to catch errors not caught anywhere else.After catching, it is best to log the error and safely shut down the app.
Examples
Node.js
process.on('uncaughtException', (err) => { console.error('Error caught:', err.message); });
Node.js
process.on('uncaughtException', (err) => { console.error('Uncaught exception:', err); process.exit(1); // exit after handling });
Sample Program
This program sets up a handler for uncaught exceptions. Then it calls a function that does not exist, causing an error. The handler catches it, logs the message, and exits the app.
Node.js
process.on('uncaughtException', (err) => { console.error('Caught an uncaught exception:', err.message); process.exit(1); }); // This will cause an uncaught exception nonExistentFunction();
Important Notes
Always log the error details to help with debugging.
It is recommended to exit the process after handling an uncaught exception to avoid unstable state.
Do not rely on this for normal error handling; use try-catch blocks where possible.
Summary
Use process.on('uncaughtException') to catch errors not handled elsewhere.
Log the error and exit the app safely to avoid unpredictable behavior.
This helps keep your Node.js app more stable and easier to debug.
Practice
1. What is the primary purpose of using
process.on('uncaughtException') in a Node.js application?easy
Solution
Step 1: Understand the role of uncaught exceptions
Uncaught exceptions are errors that happen but are not caught by any try-catch block or error handler in the code.Step 2: Purpose of
This event listener catches those uncaught errors to prevent the app from crashing unexpectedly.process.on('uncaughtException')Final Answer:
To catch errors that were not handled anywhere else in the code -> Option DQuick Check:
Uncaught exceptions = catch unhandled errors [OK]
Hint: Remember: uncaughtException catches errors missed by try-catch [OK]
Common Mistakes:
- Thinking it handles normal HTTP requests
- Assuming it restarts the server automatically
- Confusing it with logging user actions
2. Which of the following is the correct syntax to listen for uncaught exceptions in Node.js?
easy
Solution
Step 1: Identify the correct event listener method
Node.js usesprocess.onto listen for events like 'uncaughtException'.Step 2: Verify the event name and callback
The event name is exactly 'uncaughtException' and the callback receives the error object.Final Answer:
process.on('uncaughtException', (err) => { console.error(err); }); -> Option CQuick Check:
Use process.on for events [OK]
Hint: Use process.on for event listening, not catch or listen [OK]
Common Mistakes:
- Using process.catch instead of process.on
- Using process.listen or process.handle which don't exist
- Misspelling the event name
3. Consider the following Node.js code snippet:
What will be the output when this code runs?
process.on('uncaughtException', (err) => {
console.log('Caught:', err.message);
});
throw new Error('Oops!');What will be the output when this code runs?
medium
Solution
Step 1: Understand the uncaughtException handler
The handler logs the error message prefixed with 'Caught:'.Step 2: The thrown error triggers the handler
The thrown error 'Oops!' is caught by the listener and logged as 'Caught: Oops!'.Final Answer:
Caught: Oops! -> Option BQuick Check:
Uncaught error triggers handler output [OK]
Hint: Thrown error triggers uncaughtException handler output [OK]
Common Mistakes:
- Expecting the program to crash immediately
- Thinking the error message prints with 'Error:' prefix
- Assuming no output because error is ignored
4. You wrote this code to catch uncaught exceptions:
But the program crashes after the error is logged. What is the best fix?
process.on('uncaughtException', (error) => {
console.log('Error:', error.message);
});
setTimeout(() => {
throw new Error('Fail');
}, 1000);But the program crashes after the error is logged. What is the best fix?
medium
Solution
Step 1: Understand uncaughtException behavior
After catching, the app is in an unstable state and should exit safely.Step 2: Add process.exit(1) to stop the app
Callingprocess.exit(1)after logging ensures the app stops cleanly.Final Answer:
Add process.exit(1); inside the handler after logging -> Option AQuick Check:
Exit after uncaughtException to avoid unstable state [OK]
Hint: Exit process after uncaughtException to avoid crashes [OK]
Common Mistakes:
- Ignoring the need to exit after catching
- Trying to catch error inside setTimeout instead
- Using wrong event name 'error' instead of 'uncaughtException'
5. You want to log uncaught exceptions and then restart your Node.js server automatically. Which approach correctly combines handling uncaught exceptions and restarting the app?
hard
Solution
Step 1: Handle uncaught exceptions by logging and exiting
Inside the handler, log the error and callprocess.exit(1)to stop the app safely.Step 2: Use an external tool or script to restart the server
Node.js itself does not restart automatically; tools like PM2 or systemd can restart on exit.Final Answer:
Use process.on('uncaughtException') to log error, then call process.exit(1), and use a separate script or tool to restart the server -> Option AQuick Check:
Log + exit + external restart tool = correct approach [OK]
Hint: Exit on error, restart externally (PM2/systemd) for stability [OK]
Common Mistakes:
- Trying to restart server inside uncaughtException handler
- Using process.on('exit') to catch errors (wrong event)
- Wrapping entire app in try-catch which misses async errors
