gpt4 book ai didi

javascript - 在跟踪堆栈/错误对象的行号中获取文件名

转载 作者:行者123 更新时间:2023-11-30 14:52:02 25 4
gpt4 key购买 nike

我正在改进 Node.js/express 中的错误处理。

有没有办法获取我的代码中发生此错误的文件名和行号?

error-handler.js,使用console.trace,只是处理错误的路由...而不是错误实际发生的地方。


class FacebookErr extends Error {
constructor(httpCode, ...args) {
super(...args)
Error.captureStackTrace(this, FacebookErr);
this.name = 'FacebookErr';
this.date = new Date();
this.httpCode = httpCode;
}
}

  fetch(uri)
.then(status)
.then(toJson)
.then(getUserInfo)
.catch((err) => {
next(new FacebookErr(500, err));
});

Trace: FacebookErr: ReferenceError: uri is not defined
at log (/home/one/github/dolphin/app/error-handler.js:4:11)
at Layer.handle_error (/home/one/github/dolphin/node_modules/express/lib/router/layer.js:71:5)
at trim_prefix (/home/one/github/dolphin/node_modules/express/lib/router/index.js:315:13)
at /home/one/github/dolphin/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/home/one/github/dolphin/node_modules/express/lib/router/index.js:335:12)
at Immediate.next (/home/one/github/dolphin/node_modules/express/lib/router/index.js:275:10)
at Immediate.<anonymous> (/home/one/github/dolphin/node_modules/express/lib/router/index.js:635:15)
at runCallback (timers.js:783:20)
at tryOnImmediate (timers.js:743:5)
at processImmediate [as _immediateCallback] (timers.js:714:5)
Sun Dec 24 2017 13:39:37 GMT-0600 (CST)

最佳答案

使用正则表达式...以下将为您提供堆栈跟踪中第一个文件的文件名(完整路径)、行号和列号:

const [, filename, line, column ] = err.stack.match(/\/([\/\w-_\.]+\.js):(\d*):(\d*)/)

如果你想获取项目中第一个文件的信息,而不是 node_modules 中的文件:

const regEx =  = new RegExp(`${process.cwd()}\\/(?!node_modules\\/)([\\/\\w-_\\.]+\\.js):(\\d*):(\\d*)`)
const [, filename, line, column ] = err.stack.match(regEx)

关于javascript - 在跟踪堆栈/错误对象的行号中获取文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47963636/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com