NeilFraser / JS-Interpreter

A sandboxed JavaScript interpreter in JavaScript.
Apache License 2.0
1.96k stars 352 forks source link

JS-Interpreter errors and script errors distinction #244

Closed FranckFreiburger closed 1 year ago

FranckFreiburger commented 1 year ago

In the following statement:

try {
  interpreter.step()
} catch(ex) {
}

How to distinguish between a JS-Interpreter internal errors and a script error (both are instanceof Error) ?

I would like to forward script error to the callee (including the .stack), but only in the case of script error, other errors may contain private data (like script path)

NeilFraser commented 1 year ago

You're good at raising interesting questions.

The code in question is unwind (around line 3191 of interpreter.js). That's where pseudo errors are converted to real errors before being thrown. One option would be to add an ad-hoc property to these errors just before the final throw statement:

realError.fromInterpreter = true;

A less-elegant solution (but one that doesn't involve changing interpreter.js) would be to look at the 'stack' property of the error and see if it matches /(code|polyfills|appendCode|function|eval)\d*:\d+:\d+/. Alternatively, check to see if the 'stack' property matches /(acorn|interpreter)\.js/.

Neither of the above solutions (a non-standard property or sniffing the stack string) are particularly good. We do have one property that might help: the interpreter's .value property. If an error is thrown, the .value remains set to the last statement value computed in the code. This is actually bad, since it's not the interpreter's intended output. What about setting it to the thrown error if it's a pseudo error, and setting it to be undefined if it's a real JavaScript error?

FranckFreiburger commented 1 year ago

What about setting it to the thrown error if it's a pseudo error, and setting it to be undefined if it's a real JavaScript error?

That would really be a wonderful solution !! Thanks Neil

NeilFraser commented 1 year ago

Pull, and you should receive this change.

FranckFreiburger commented 1 year ago

wow fast ! thanks