Open In App

How to Show the Line which Cause the Error in Node.js ?

Last Updated : 24 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Debugging is a critical part of software development. When an error occurs in a Node.js application, understanding exactly where it happened is essential for diagnosing and fixing the problem. Node.js provides several ways to pinpoint the line of code that caused an error. This article explores these methods, including using stack traces, enhanced debugging tools, and third-party libraries.

Understanding Stack Traces

When an error occurs in Node.js, a stack trace is typically printed to the console. A stack trace is a report of the active stack frames at a certain point in time during the execution of a program. It helps developers identify where an error occurred by providing a trace of function calls that led to the error.

Problem Statement: We are trying to create an example that will cause an error in understanding the topic clearly

JavaScript
// main.js

const fs = require('fs')
const helper = require('./helper')

try {
    // Missing 3rd parameter
    const values = helper(1, 2) 
    console.log(values)
} catch (e) {
    console.warn('Error:', e)
}
JavaScript
// helper.js

module.exports = (a, b, c) => {
    if (typeof a === 'undefined')
        throw new Error("Parameter A is not set")
    if (typeof b === 'undefined')
        throw new Error("Parameter B is not set")
    if (typeof c === 'undefined')
        throw new Error("Parameter C is not set")
        
    return { a, b, c }
}


Steps to run the application: Now run the main.js file with the following command:

node main.js

Output:

Here, the file helper.js throws an error because parameter "c" is not passed while invoking the function in file main.js. Now, let's discuss how we can print the exact line that causes the error.

Solution:

We will solve the above problem by going through the error stack and finding the exact line and line number that throws the error.

Example 1: This example will illustrate how to show the line which caused the error in NodeJS:

JavaScript
// main.js

const fs = require('fs')
const helper = require('./helper')

try {
    // Missing 3rd parameter
    const values = helper(1, 2)
    console.log(values)
} catch (e) {
    console.warn('Error:', e.message)

    // We iterate through all the files 
    // mentioned in the error stack and 
    // find the line and line number 
    // that resulted in the error
    e.stack
        .split('\n')
        .slice(1)
        .map(r => r.match(/\((?<file>.*):(?<line>\d+):(?<pos>\d+)\)/))
        .forEach(r => {
            if (r && r.groups && r.groups.file.substr(0, 8) !== 'internal') 
            {
                const { file, line, pos } = r.groups
                const f = fs.readFileSync(file, 'utf8').split('\n')
                console.warn('  ', file, 'at', line + ':' + pos)
                console.warn('    ', f[line - 1].trim())
            }
        })
}
JavaScript
// helper.js

module.exports = (a, b, c) => {
    if (typeof a === 'undefined')
        throw new Error("Parameter A is not set")
    if (typeof b === 'undefined')
        throw new Error("Parameter B is not set")
    if (typeof c === 'undefined')
        throw new Error("Parameter C is not set")
        
    return { a, b, c }
}

Steps to run the application: Now run the main.js file with the following command:

node main.js

Output:

Example 2: This example will illustrate how to show the line which caused the error in NodeJS:

JavaScript
// main.js

const fs = require('fs')
const multiplyBy2 = require('./helper')

try {
    const values = multiplyBy2()
    console.log(values)
} catch (e) {
    e.stack
        .split('\n')
        .slice(1)
        .map(r => r.match(/\((?<file>.*):(?<line>\d+):(?<pos>\d+)\)/))
        .forEach(r => {
            if (r && r.groups && r.groups.file.substr(0, 8) !== 'internal') 
            {
                const { file, line, pos } = r.groups
                const f = fs.readFileSync(file, 'utf8').split('\n')
                console.warn('  ', file, 'at', line + ':' + pos)
                console.warn('    ', f[line - 1].trim())
            }
        })
}
JavaScript
// helper.js

module.exports = (num) => {
    if (!num)
        throw new Error("Parameter num is not set")
        
    return num * 2;
}


Steps to run the application: Now run the main.js file with the following command:

node main.js

Output:


Next Article

Similar Reads