When I catch an error in ExtendScript, I would like to be able to log its stack trace. It appears that errors do not contain stack traces in ExtendScript, so I'm playing around with the idea of adding stack traces to errors.
The only way I know of to get a stack trace is $.stack
. The field $.stack
contains the current stack trace at the moment that you access the field.
My first attempt was to create my own error object that includes the stack. The Error
object is very special in that it can get the line and filename of the code that created it. For example,
try {
throw new Error("Houston, we have a problem.");
}
catch (e) {
$.writeln("Line: " + e.line);
$.writeln("File: " + e.fileName);
$.writeln("Message: " + e.message);
}
Will print:
Line: 2
File: ~/Desktop/Source1.jsx
Message: Houston, we have a problem.
I don't think it's possible to create your own object with this ability. The closest I can get is this:
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);
}
Which prints:
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)
Here we can see that I'm creating my own error object and explicitly passing it the line and file name (since MyError can't figure that out on its own). I've also included the current stack when the error gets created.
This works fine when I call my own error object, but it doesn't work when other code calls the regular Error object or when an error is generated automatically (e.g. by illegal access). I want to be able to get the stack trace of any error, no matter how it is generated.
Other approaches might be to modify Error
's constructor, modify Error
's prototype, or replace the Error
object entirely. I haven't been able to get any of these approaches to work.
Another idea would be to put a catch block in every single method of my code and add the current stack to the error if it doesn't already have one. I would like to avoid this option if possible.
I'm out of ideas. Is there any way to get the stack trace of errors?