Concept:
Robust error handling is crucial in Node.js because unhandled errors can crash your server. Also, understanding the Node.js process lifecycle (how it starts, manages resources, and exits) is vital for building stable systems.
Node.js categorizes errors into:
- Operational errors (expected: file not found, DB unavailable)
- Programmer errors (bugs: undefined vars, logic flaws)
Best practice: catch operational errors, crash on programmer errors.
Real-World Scenario:
You're building a backend that connects to a DB, reads files, and makes API calls. You must:
- Handle all operational errors gracefully
- Keep the app alive (using clusters or PM2)
- Exit cleanly on critical failures (like uncaught exceptions)
Interview Questions:
- What's the difference between
uncaughtException and unhandledRejection?
- What is
SIGTERM vs SIGKILL
- When should you use
process.exit()?
- How do you handle fatal errors gracefully?
- How can you catch async errors in Express middleware?
- How do you shut down a Node.js server safely?