当我在 ExtendScript 中发现错误时,我希望能够记录其堆栈跟踪。看来错误在 ExtendScript 中不包含堆栈跟踪,因此我正在考虑向错误添加堆栈跟踪的想法。
据我所知,获取堆栈跟踪的唯一方法是$.stack
。字段 $.stack
包含您访问该字段时的当前堆栈跟踪。
我的第一次尝试是创建我自己的包含堆栈的错误对象。 Error
对象非常特殊,因为它可以获取创建它的代码的行和文件名。例如,
try {
throw new Error("Houston, we have a problem.");
}
catch (e) {
$.writeln("Line: " + e.line);
$.writeln("File: " + e.fileName);
$.writeln("Message: " + e.message);
}
将打印:
Line: 2
File: ~/Desktop/Source1.jsx
Message: Houston, we have a problem.
我认为不可能用这种能力创建你自己的对象。我能得到的最接近的是:
function MyError(msg, file, line) {
this.message = msg;
this.fileName = file;
this.line = line;
this.stack = $.stack;
}
try {
throw new MyError("Houston, we have a problem.", $.fileName, $.line);
}
catch (e) {
$.writeln("Line: " + e.line);
$.writeln("File: " + e.fileName);
$.writeln("Message: " + e.message);
$.writeln("Stack: " + e.stack);
}
打印内容:
Line: 9
File: ~/Desktop/Source2.jsx
Message: Houston, we have a problem.
Stack: [Source3.jsx]
MyError("Houston, we have a p"...,"~/Desktop/Source2.js"...,9)
在这里我们可以看到我正在创建自己的错误对象并显式地向其传递行和文件名(因为 MyError 无法自行解决)。我还包括了创建错误时的当前堆栈。
当我调用自己的错误对象时,这可以正常工作,但当其他代码调用常规错误对象或自动生成错误时(例如,通过非法访问),它就不起作用。我希望能够获取任何错误的堆栈跟踪,无论它是如何生成的。
其他方法可能是修改 Error
的构造函数、修改 Error
的原型(prototype)或完全替换 Error
对象。我无法让这些方法发挥作用。
另一个想法是在代码的每个方法中放置一个 catch block ,并将当前堆栈添加到错误中(如果还没有)。如果可能的话,我想避免这个选项。
我没主意了。有什么方法可以获取错误的堆栈跟踪吗?
最佳答案
它并不完美,但我找到了部分解决方案。
事实 1:Error.prototype
是一个 Error 对象。
事实 2:每当创建错误时都会调用 Error.prototype.toString
方法。
事实 3:Error.prototype.toString
字段可以修改。
该方法通常只返回字符串“Error”,因此我们可以将其替换为我们自己的存储堆栈的方法,然后返回字符串“Error”。
Error.prototype.toString = function() {
if (typeof this.stack === "undefined" || this.stack === null) {
this.stack = "placeholder";
// The previous line is needed because the next line may indirectly call this method.
this.stack = $.stack;
}
return "Error";
}
try {
throw new Error("Houston, we have a problem.");
}
catch (e) {
$.writeln("Line: " + e.line);
$.writeln("File: " + e.fileName);
$.writeln("Message: " + e.message);
$.writeln("Stack: " + e.stack);
}
结果:
Line: 11
File: ~/Desktop/Source10.jsx
Message: Houston, we have a problem.
Stack: [Source10.jsx]
toString()
它有效!唯一的问题是自动错误。
Error.prototype.toString = function() {
if (typeof this.stack === "undefined" || this.stack === null) {
this.stack = "placeholder";
// The previous line is needed because the next line may indirectly call this method.
this.stack = $.stack;
}
return "Error";
}
try {
var foo = null;
foo.bar;
}
catch (e) {
$.writeln("Line: " + e.line);
$.writeln("File: " + e.fileName);
$.writeln("Message: " + e.message);
$.writeln("Stack: " + e.stack);
}
结果:
Line: 12
File: ~/Desktop/Source12.jsx
Message: null is not an object
Stack: undefined
所以它并不适用于所有错误,而是适用于进度。
关于adobe - 获取 ExtendScript 中错误的堆栈跟踪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16201574/