Node.js Error Handling and Debugging

Handling Errors in Node.js Applications:

There are two types of Errors in Node.js:

Synchronous Errors: Errors that occur during the execution of synchronous code.

Asynchronous Errors: Errors that occur during the execution of asynchronous code (callbacks, promises, async/await).

Synchronous Error Handling:

You can use try-catch blocks to handle errors in synchronous code.

                                    
try {
    // Synchronous code that might throw an error
    let result = someFunction();
    console.log(result);
} catch (error) {
    console.error('Error occurred:', error.message);
}

                                    
                                

Asynchronous Error Handling:

Asynchronous Error Handling: For callbacks, handle errors by checking for error arguments.

                                    
fs.readFile('file.txt', (err, data) => {
    if (err) {
        console.error('Error reading file:', err);
        return;
    }
    console.log('File data:', data.toString());
});

                                    
                                

For promises, use .catch() to handle errors.

                                    
    someAsyncFunction()
    .then(result => {
        console.log(result);
    })
    .catch(error => {
        console.error('Error occurred:', error.message);
    });
                                    
                                

For async/await, use try-catch blocks.

                                    
async function readFile() {
    try {
        const data = await fs.promises.readFile('file.txt');
        console.log('File data:', data.toString());
    } catch (error) {
        console.error('Error reading file:', error.message);
    }
}
readFile();

                                    
                                

Centralized Error Handling:

The Express.js applications can use middleware to handle errors centrally.

                                    
const express = require('express');
const app = express();

// Route handler
app.get('/', (req, res, next) => {
    try {
        throw new Error('Something went wrong');
    } catch (error) {
        next(error); // Pass the error to the error handling middleware
    }
});

// Error handling middleware
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).send('Internal Server Error');
});

app.listen(3000, () => {
    console.log('Server running at http://localhost:3000');
});

                                    
                                

Debugging Node.js Applications:

Built-in Debugging Tools:

Node.js Debugger:

  • Start the Node.js application with the --inspect flag.
                                    
                                    node --inspect app.js
                                    
                                

  • In above example will start the application in debug mode, and you can access it via chrome://inspect in Google Chrome.

Debugging with 'console.log':

To use console.log to print variables and trace the execution flow.

                                    
                                    console.log('Variable value:', variable);
                                    
                                

Third-Party Debuggers:

  • Visual Studio Code Debugger:
    • The Visual Code has built-in support for debugging Node.js applications.
    • Create a launch.json configuration file.
                                    
{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Launch Program",
            "program": "${workspaceFolder}/app.js"
        }
    ]
}
                                    
                                

  • Set breakpoints in your code and start debugging using the Debug panel in VS Code.
  • Debugger Library (debug):
    • The debug library provides a simple way to enable and disable debug logging.
    • Install the library:
                                    
                                    npm install debug
                                    
                                

  • Use it in your code:
                                    
const debug = require('debug')('app');

debug('Starting application...');