Thursday, 19 December 2024

Node.js handle uncaught exceptions

Node.js handle uncaught exceptions Node.js handle uncaught exceptions Node.js handle uncaught exceptions

const express = require('express');

const app = express();

// Middleware to parse JSON requests
app.use(express.json());

// A sample route
app.get('/', (req, res) => {
    res.send('Welcome to the Express.js app!');
});

// An example of a route with a potential error
app.get('/error', (req, res) => {
    throw new Error('This is an uncaught exception!');
});

// Global error handling middleware
app.use((err, req, res, next) => {
    console.error('Error caught by middleware:', err.message);
    res.status(500).json({ message: 'Internal Server Error' });
});

// Start the server
const PORT = 3000;
const server = app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});

// Handle uncaught exceptions
process.on('uncaughtException', (err) => {
    console.error('Uncaught Exception:', err.message);
    console.error(err.stack);

    // Perform cleanup if necessary, then exit
    server.close(() => {
        console.log('Server closed due to uncaught exception');
        process.exit(1); // Exit with a failure code
    });
});

// Handle unhandled promise rejections
process.on('unhandledRejection', (reason, promise) => {
    console.error('Unhandled Rejection at:', promise, 'reason:', reason);

    // Perform cleanup if necessary
    server.close(() => {
        console.log('Server closed due to unhandled rejection');
        process.exit(1); // Exit with a failure code
    });
});

No comments:

Post a Comment