Open In App

How to show the line which cause the error in Node.js ?

Last Updated : 29 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how to make the error stack more verbose and readable, and print the exact line that causes an error in a node.js program. 

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

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)
}


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.

Approach & 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:

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())
            }
        })
}


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:

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())
            }
        })
}


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:

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads