Error Handling Best Practices
Error Handling: Graceful Degradation & Resilience
In robust Node.js architectures, errors are broadly classified into two taxonomies: Operational Errors and Programmer Errors.
Operational Errors
These are anticipated runtime failures—network timeouts, database connection drops, or invalid user inputs. The application must identify these, report them, and gracefully continue serving traffic.
Programmer Errors
These represent absolute bugs in the logic, such as TypeErrors or attempts to read properties of undefined objects. Because the application enters an unpredictable state, the safest resolution is to crash the process and allow the supervisor (e.g., PM2 or Kubernetes) to restart a clean instance.
Global Safenets
Global listeners like uncaughtException and unhandledRejection exist strictly to execute synchronous cleanup (closing logs) before exiting using process.exit(1). Swallowing errors here is an egregious anti-pattern leading to memory leaks.