Q47: How should global process exceptions (`uncaughtException`, `unhandledRejection`) be handled in Express apps?

Difficulty:AdvancedTopic:Resilience

Uncaught synchronous exceptions or unhandled promise rejections can leave the application state corrupted. The safest recovery strategy is logging the error, closing server connections, and letting process managers (PM2/Kubernetes) restart the container instance cleanly.

Global Exception Handler Process Exit
process.on('unhandledRejection', (reason, promise) => {
  console.error('Unhandled Rejection at:', promise, 'reason:', reason);
  // Gracefully exit and let process manager restart
  server.close(() => process.exit(1));
});

Exiting corrupted process instances prevents unpredictable application behavior.

Key Takeaways
  • Never ignore process-level unhandled rejections.

  • Always log error details and trigger a clean container restart.