tezvyn:

Handling uncaughtException and unhandledRejection

AI-drafted, machine-checkedSource: interviewadvanced
WHAT IT TESTS

process-level last-resort error handling.

OUTLINE

listen on process for uncaughtException and unhandledRejection, log the error, stop accepting new work, drain in-flight requests, then exit non-zero for a supervisor to restart.

WHAT THIS TESTS Whether you understand these are safety nets for logging and orderly shutdown, not a way to keep a broken process running.

A GOOD ANSWER COVERS uncaughtException fires when a synchronous error bubbles to the top with no handler; unhandledRejection fires when a promise rejects and nothing catches it. You register process.on('uncaughtException', ...) and process.on('unhandledRejection', ...) as a global last resort. The robust strategy inside the handler is: log the full error with stack and context to your logging system, stop accepting new requests (close the HTTP server), give in-flight requests a short bounded grace period to complete, then call process.exit with a non-zero code so a process manager like PM2, systemd, or Kubernetes restarts a fresh instance. You should also use a watchdog timer to force-exit if graceful shutdown stalls. Resuming normal operation is unsafe because reaching these handlers means an error escaped all your handling, so the process state is unknown and possibly corrupted, and continuing risks serving wrong results or leaking resources.

COMMON WRONG ANSWERS Using these handlers to swallow errors and keep running, not exiting afterward, or doing heavy async cleanup without a forced-exit timeout.

LIKELY FOLLOW-UPS Why the process state is untrustworthy, the difference from operational error handling, zero-downtime restarts and clustering, and forcing exit on a timeout.

ONE CONCRETE EXAMPLE process.on('uncaughtException', (err) => { logger.fatal(err); server.close(() => process.exit(1)); setTimeout(() => process.exit(1), 10000).unref(); }); This logs the fatal error, stops accepting connections, lets active requests drain for up to ten seconds, then exits so the orchestrator launches a clean replacement instead of leaving a possibly corrupted process running.

Read the original → nodejs.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.