javascript node.js 在 try catch 中获取行号?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5802840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript node.js getting line number in try catch?
提问by Mark
I'm using try catch on a node.js script:
我在 node.js 脚本上使用 try catch:
try {} catch (err) {console.log(err)}
I get an output like this:
我得到这样的输出:
{ stack: [Getter/Setter],
arguments: [ 'undefined' ],
type: 'called_non_callable',
message: [Getter/Setter] }
Is there an easy way to make this more informative? Include line numbers and function names and such?
有没有一种简单的方法可以让这个信息更丰富?包括行号和函数名等等?
回答by schaermu
Those [Getter/Setter]
members indicate further information available on the error object. You can easily dump the contents of those getters/setters using a small helper function (very trivial implementation, further refinement is up to you)
这些[Getter/Setter]
成员指示有关错误对象的更多信息。您可以使用一个小的辅助函数轻松转储这些 getter/setter 的内容(非常简单的实现,进一步细化取决于您)
function dumpError(err) {
if (typeof err === 'object') {
if (err.message) {
console.log('\nMessage: ' + err.message)
}
if (err.stack) {
console.log('\nStacktrace:')
console.log('====================')
console.log(err.stack);
}
} else {
console.log('dumpError :: argument is not an object');
}
}
try {
not_defined.function_call();
} catch(err) {
dumpError(err);
}
You could also extend the Object.prototype
for improved accessability (so you could use err.dumpError()), although extending Object.prototype
bears the risk of overwriting existing functionality.
您还可以扩展Object.prototype
以提高可访问性(因此您可以使用 err.dumpError()),尽管扩展Object.prototype
承担覆盖现有功能的风险。