← Back to Node.js, page 2

nodejs-0029 · Medium mid

What happens on an unhandled promise rejection or an uncaught exception in Node.js, and how should you handle them?

Since Node 15 an unhandled rejection throws and ends the process with exit code 1, unless an 'unhandledRejection' handler exists. An uncaught exception also ends the process unless an 'uncaughtException' handler exists. Handlers should log, flush, and exit, because the process may be in an unknown state.

Full answer

An unhandled rejection is a promise that rejects when nothing has attached a .catch or try/await around it. By default, Node 15 and later treat it like an uncaught exception: it prints the error and exits with code 1. Older versions only printed a warning.

An uncaught exception is a thrown error that no try/catch caught. The default is to print the stack and exit with code 1.

You can register handlers:

  • process.on('unhandledRejection', (reason, promise) => { ... })
  • process.on('uncaughtException', (err, origin) => { ... })

Use them as a last line of defence for logging and clean-up, not for carrying on. After an unexpected error, application state may be half updated: a lock not released, a transaction open, a socket half written. The safe sequence is: log the error with context, stop accepting new work, finish or abandon current work with a timeout, and exit with a non-zero code. A process manager (systemd, Docker, Kubernetes, pm2) then starts a fresh process.

Prevent the problem at the source: await or return every promise, add .catch to fire-and-forget calls, and use ESLint rules such as no-floating-promises.

Also remember that process.on('exit') callbacks can only run synchronous code, so flush logs before that point.

javascript
const { spawnSync } = require('node:child_process');

function runChild(label, code) {
  const r = spawnSync(process.execPath, ['-e', code], { encoding: 'utf8' });
  console.log(label);
  console.log('  exit code:', r.status);
  console.log('  stdout:   ', r.stdout.trim() || '(empty)');
  console.log('  stderr mentions the error:', r.stderr.includes('marks service down'));
}

runChild('1. unhandled rejection, no handler',
  "Promise.reject(new Error('marks service down'));");

runChild('2. unhandled rejection with a handler that logs and exits',
  `process.on('unhandledRejection', (reason) => {
     console.log('logged:', reason.message);
     process.exit(1);
   });
   Promise.reject(new Error('marks service down'));`);

runChild('3. uncaught exception with a handler that logs and exits',
  `process.on('uncaughtException', (err, origin) => {
     console.log('logged:', err.message, '| origin:', origin);
     process.exitCode = 1;
     process.exit();
   });
   setTimeout(() => { throw new Error('marks service down'); }, 0);`);

Each case runs in a child process, so the parent keeps running. Cases 1 and 2 are errors on purpose, shown through exit codes. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): 1. unhandled rejection, no handler exit code: 1 stdout: (empty) stderr mentions the error: true 2. unhandled rejection with a handler that logs and exits exit code: 1 stdout: logged: marks service down stderr mentions the error: false 3. uncaught exception with a handler that logs and exits exit code: 1 stdout: logged: marks service down | origin: uncaughtException stderr mentions the error: false

Key points

  • Node 15 and later exit with code 1 on an unhandled rejection by default.
  • Handlers are for logging and graceful exit, not for continuing.
  • Let a supervisor restart the process.
  • Prevent them with await, return and lint rules.

Common mistakes

  • Using an uncaughtException handler to keep the server running as if nothing happened.
  • Calling process.exit() immediately and cutting off pending log writes.
  • Throwing inside a promise chain without a final catch.
  • Assuming async functions called without await are safe.

Follow-ups

  • How would you shut down gracefully after an uncaught exception?
  • What does the --unhandled-rejections flag change?
  • Why can finally blocks not run after process.exit()?

Tips

  • Name the exit code (1) and the Node version (15) that changed the default.
  • Say 'log, stop accepting work, exit, let the supervisor restart'.
  • Mention lint rules for floating promises.