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

← All Node.js Developer questions