【问题标题】:how to show the line which caused the error in NodeJS?如何显示导致 NodeJS 错误的行?
【发布时间】:2021-11-18 09:41:01
【问题描述】:

考虑我的情况:我正在创建一个节点 js 模块示例 xyz.js。 main.js 是我的主节点文件,例如从 xyz 调用的函数由于传递的参数无效而导致错误,现在我只想控制台行和导致错误的 main.js 的行号.

【问题讨论】:

  • 原生错误堆栈有什么问题?
  • 它可以工作,但它并不能准确地指出一行中的错误位置。当您想要获取错误的完整详细信息时,它很有用,但当您只想突出显示错误所在的行时,它就没有用了
  • 我猜你可以捕获错误,解析堆栈,使用fs 读取文件并控制台打印该行,但是,我会发现原始堆栈通常更好用
  • stack 使用语法Object.<anonymous> ( file path) 表示行号,我使用搜索字符串方法解决了这个问题。虽然不是一个完美的解决方案,但暂时解决了我的问题

标签: javascript node.js function error-handling


【解决方案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 }
}

但正如我所说,最初的 Error 堆栈对我来说更有意义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-30
    • 2023-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多