How to Use process.on for Error Handling in Node.js
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.
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.
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);
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.
/* 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
| Event | Description | When to Use |
|---|---|---|
| uncaughtException | Catches exceptions not caught by try/catch | Log error and exit process |
| unhandledRejection | Catches unhandled Promise rejections | Log promise errors and handle cleanup |
| exit | Fires when process is about to exit | Cleanup resources before exit |