在 JavaScript 中捕获/处理异常时,如何确定异常发生时的调用堆栈是什么?(如果可能的话,行号是什么)
try
{
// etc...
}
catch (ex)
{
// At this point here I want to be able to print out a detailed exception
// message, complete with call stack, and if possible line numbers.
}
在 JavaScript 中捕获/处理异常时,如何确定异常发生时的调用堆栈是什么?(如果可能的话,行号是什么)
try
{
// etc...
}
catch (ex)
{
// At this point here I want to be able to print out a detailed exception
// message, complete with call stack, and if possible line numbers.
}
每个浏览器对此的处理方式不同,因此没有通用的方法来做到这一点。This blog post有一些很好的代码可以为大多数支持的浏览器转储堆栈跟踪。我认为没有提供行号的好方法。
如果你特别想调试一个函数,Firebug有一个很好的堆栈跟踪函数(vis console.trace())。
看看这个。
一种分析可用信息的方法:
try
{
doInit();
} catch(err)
{
var vDebug = "";
for (var prop in err)
{
vDebug += "property: "+ prop+ " value: ["+ err[prop]+ "]\n";
}
vDebug += "toString(): " + " value: [" + err.toString() + "]";
status.rawValue = vDebug;
}
我发现在 IE 下运行的 JavaScript 中,无法在捕获异常时捕获堆栈跟踪。根据此PDF,在 IE 中获取堆栈跟踪的唯一方法是您不处理异常。
对于大多数错误,您可以检查堆栈跟踪,其中将包括错误位置的行号和列号:
try {
throw new Error('foo');
} catch(e) {
console.log(e.message);
console.log(e.stack);
const [, lineno, colno] = e.stack.match(/(\d+):(\d+)/);
console.log('Line:', lineno);
console.log('Column:', colno);
}
第 13 行是正确的,因为这是 HTML 中来自 stacksnippets.net 响应中错误所在的行:
请注意,这不适用于抛出的非错误,例如throw null
or throw 'foo'
(正是出于这个原因,不建议这样做)。