Siubaak / sval

A javascript interpreter written in javascript
https://jsbin.com/kehahiqono/edit?js,console
MIT License
372 stars 50 forks source link

impossible to catch generated ReferenceError #105

Closed damianofalcioni closed 6 days ago

damianofalcioni commented 1 week ago

Hi, when the runned code try to access an object that has not been imported it generate a ReferenceError that cannot be catch.

ReferenceError: myObj is not defined
    at ...\node_modules\sval\dist\sval.js:1990:21
...
Node.js v20.16.0
npm error Lifecycle script `run` failed with error:
npm error code 1

There is a way to handle it? I've seen in the code there is a throwErr option but is not exposed.

Thanks

PS: I'm importing Sval as an ES6 module in Node

Siubaak commented 6 days ago

What about this? Does it work for your scenario?

const interpreter = new Sval()

try {
  interpreter.run('console.error(myObj)')
} catch (err) {
  console.error('Caught error')
}
Siubaak commented 6 days ago

Could you offer a repo or something to reproduce this bug? It seems I can't reproduce it with sval@0.5.2 on node v20.12.2.

image
damianofalcioni commented 6 days ago

when the code is inside an async it is not catch:

import Sval from 'sval';

const interpreter = new Sval();
try {
  interpreter.run(`
!async function () {
  console.log(myObj);
}();`);
} catch (e) {
  console.error('err');
}
Siubaak commented 6 days ago

Right, that's how async behaves. The async function doesn't run in the current loop, so try-catch can't catch the error synchronously. Try to catch the error inside:

import Sval from 'sval';

const interpreter = new Sval();

interpreter.run(`
!async function () {
  try {
    console.log(myObj);
  } catch (e) {
    console.error('err');
  }
}();`);
damianofalcioni commented 6 days ago

Thanks, that solved the issue