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.
CodePudding user response:
// 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.