2

Consider my situation : I am creating a node js module example xyz.js . main.js is my main node file, for example a function is called from xyz and it caused the error due to invalid arguments passed, now I want to just console the line and the line number of main.js which caused the error.

5
  • What's wrong with the native error stack? Commented Sep 25, 2021 at 14:06
  • It works but it doesnot exactly point the place of error in one line. It is useful when you want to get full detail of error, but not when you just want to higlight the line from where the error is coming Commented Sep 25, 2021 at 15:01
  • 1
    I guess you can catch the error, parse the stack, read the file with fs and console print that line, however, I'd find the original stack a generally better use Commented Sep 25, 2021 at 15:32
  • stack indicates the line number using syntax Object.<anonymous> ( file path) and I solved this using search string method. Though not a perfect solution but temporarily it solved my problem Commented Sep 27, 2021 at 8:38
  • Any solution? I think the latest nodejs version minify the code at runtime. On my case, the error point me to the line 1 but in that line only a simple require or import is. Debugging, the real error was on line 50. Commented Aug 4, 2022 at 14:21

1 Answer 1

1
// main.js

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

try {
    const values = xyz(1, 2) // missing 3rd parameter
    console.log(values)
} catch (e) {
    console.warn('Error:', e.message)
    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())
            }
        })
}
// xyz.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 }
}

But as I've said, the original Error's stack makes more sense to me.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.