Node.js Developer interview question · Most asked
How should errors be handled in a Node.js application?
Summary
Use try/catch with async/await, always handle promise rejections, pass errors to framework error handlers (e.g., Express next(err)), distinguish operational errors (timeouts, invalid input) from programmer errors (bugs), and crash and restart on unknown states.
Longer Answer
Process-level handlers (process.on('uncaughtException'), 'unhandledRejection') should log and exit gracefully, not keep running in a corrupted state; a supervisor (systemd, Kubernetes, PM2) restarts the process. Use Error subclasses with codes, and cause to chain errors.
Code Example
class NotFoundError extends Error {
constructor(resource, options) {
super(`${resource} not found`, options);
this.name = "NotFoundError";
this.status = 404;
}
}
process.on("unhandledRejection", (reason) => {
logger.fatal({ reason }, "unhandled rejection");
process.exitCode = 1;
shutdown();
});
Key Points
- Operational vs programmer errors
- Never ignore rejections
- Log and exit on uncaught exceptions
- Custom error classes +
cause
More most-asked Node.js Developer questions
- What is Node.js and why is it well suited to I/O-heavy servers?
- What are streams in Node.js and what is backpressure?
- Explain the phases of the Node.js event loop.
- What is the difference between `process.nextTick`, Promise microtasks, `setImmediate` and `setTimeout(fn, 0)`?
- How has asynchronous code evolved in Node.js: callbacks, Promises and async/await?
- Walk through how an Express app handles a request, including errors from async handlers.
- Why is CPU-bound work a problem in Node.js and how do you handle it?
- What are the differences between CommonJS and ES modules in Node.js?