CodePark/ questions / Errors, process & signals
START PRACTICINGPRACTICE
Backend question · Node.js › Errors, process & signals

What are the uncaughtException and unhandledRejection process events? Should you use them to keep the server running?

They are process events for errors that nobody handled. No, you should not use them to keep the server running. Use them only to log the error, flush telemetry and exit.

  • uncaughtException fires when a thrown error goes all the way up to the event loop without being caught.
  • unhandledRejection fires when a promise rejects and no handler is attached within one turn of the event loop.

Without listeners, Node prints the error and exits with code 1. For rejections, this has been the default since Node 15.

Why not carry on? After an uncaught exception, the process can be in an unknown state. For example, it can have:

  • half-finished operations
  • open transactions
  • leaked resources

The official advice is to use these handlers only to log the error, flush telemetry (send the last metrics and logs) and then exit.

Run the process under a supervisor that restarts it, such as Kubernetes, systemd or PM2. Handle expected errors in the place where they happen.

  • uncaughtException fires when a thrown error reaches the event loop.
  • unhandledRejection fires when a rejected promise has no handler.
  • By default, both crash the process with exit code 1. For rejections, this is the default since Node 15.
  • The state may be corrupt, so log, clean up and exit.
  • Let a supervisor restart the process.