0
0
NodejsHow-ToBeginner · 4 min read

How to Use process.on for Error Handling in Node.js

In Node.js, use process.on to listen for error events like uncaughtException or unhandledRejection to catch errors that are not handled elsewhere. This helps you log errors or clean up before the app exits, improving reliability.
📐

Syntax

The process.on method listens for specific events on the Node.js process object. You provide the event name as the first argument and a callback function as the second. Common error events are uncaughtException and unhandledRejection.

  • event: The name of the event to listen for (e.g., uncaughtException).
  • callback: A function that runs when the event happens, receiving the error object.
javascript
process.on('event', (error) => {
  // handle error
});
💻

Example

This example shows how to catch an uncaught exception using process.on. When an error is thrown but not caught, the listener logs the error and exits the process gracefully.

javascript
process.on('uncaughtException', (err) => {
  console.error('Caught exception:', err.message);
  process.exit(1); // Exit after handling
});

// This will cause an uncaught exception
setTimeout(() => {
  throw new Error('Something went wrong!');
}, 100);
Output
Caught exception: Something went wrong!
⚠️

Common Pitfalls

Developers often misuse process.on by trying to recover from errors that should instead be handled locally. Using uncaughtException to keep the app running can cause unstable states. It's best to log the error and exit or restart the app.

Also, forgetting to exit the process after handling an uncaught exception can leave the app in a broken state.

javascript
/* Wrong way: ignoring error and continuing */
process.on('uncaughtException', (err) => {
  console.error('Error:', err.message);
  // No exit, app may be unstable
});

/* Right way: log and exit */
process.on('uncaughtException', (err) => {
  console.error('Error:', err.message);
  process.exit(1);
});
📊

Quick Reference

EventDescriptionWhen to Use
uncaughtExceptionCatches exceptions not caught by try/catchLog error and exit process
unhandledRejectionCatches unhandled Promise rejectionsLog promise errors and handle cleanup
exitFires when process is about to exitCleanup resources before exit

Key Takeaways

Use process.on('uncaughtException') to catch errors not handled elsewhere.
Always log the error and exit the process to avoid unstable states.
Use process.on('unhandledRejection') to catch unhandled Promise errors.
Avoid trying to recover from uncaught exceptions inside the listener.
Use process.on('exit') to clean up resources before the app closes.