Graceful shutdown helps your Node.js app close safely when errors happen. It stops new work, finishes current tasks, and cleans up before exiting.
0
0
Graceful shutdown on errors in Node.js
Introduction
When your server encounters an unexpected error and needs to stop without losing data.
When you want to close database connections properly before the app exits.
When you want to notify users or log important info before shutting down.
When you want to avoid crashing your app abruptly and causing bad user experience.
Syntax
Node.js
process.on('uncaughtException', (err) => { // handle error // clean up resources process.exit(1); }); process.on('SIGTERM', () => { // clean up and exit process.exit(0); });
process.on listens for system signals or errors.
Always clean up resources like database connections before exiting.
Examples
Catches unexpected errors and logs them before exiting with error code 1.
Node.js
process.on('uncaughtException', (err) => { console.error('Error caught:', err); // close server or DB here process.exit(1); });
Handles Ctrl+C (SIGINT) to shut down gracefully.
Node.js
process.on('SIGINT', () => { console.log('SIGINT received, shutting down...'); // clean up process.exit(0); });
Example of async cleanup before exiting on SIGTERM signal.
Node.js
async function shutdown() { await db.close(); console.log('Database closed'); process.exit(0); } process.on('SIGTERM', shutdown);
Sample Program
This Node.js server listens on port 3000. If you visit /error, it throws an error. The uncaughtException handler catches it, logs the message, closes the server, then exits with code 1. Pressing Ctrl+C triggers SIGINT to close the server gracefully and exit with code 0.
Node.js
import http from 'node:http'; const server = http.createServer((req, res) => { if (req.url === '/error') { throw new Error('Simulated error'); } res.end('Hello World'); }); server.listen(3000, () => { console.log('Server running on http://localhost:3000'); }); process.on('uncaughtException', (err) => { console.error('Uncaught Exception:', err.message); server.close(() => { console.log('Server closed'); process.exit(1); }); }); process.on('SIGINT', () => { console.log('SIGINT received, shutting down server'); server.close(() => { console.log('Server closed'); process.exit(0); }); });
OutputSuccess
Important Notes
Never ignore errors; always handle them to avoid crashes.
Use server.close() to stop accepting new connections before exit.
Exiting with code 0 means success; non-zero means error.
Summary
Graceful shutdown stops new work and cleans up before exiting.
Use process.on to catch errors and signals.
Always close servers and resources before exiting.