Vm2: Handle error in async callback

Created on 3 Feb 2017  ·  8Comments  ·  Source: patriksimek/vm2

Is there any way to handle error in async callback?

const {NodeVM} = require('vm2');

const vm = new NodeVM({
    timeout: 10000,
    sandbox: {}
});

try {
  vm.run(`
    setInterval(() => {
      console.log("haha")
      process.exit()              // <--- can't find a way to intercept this!
    }, 1000);

    process.exit()
  `, 'code.js');
} catch(e) {
  console.log(e.message);
}


setInterval(() => {
  console.log("haha 2")
},1000);

I'm seeking for a way to prevent whole script crashing.

feature request stale

Most helpful comment

I'm wrapping vm.run() with domain.run() and it seems to work. I don't know if it has any side effects though..

let domain = Domain.create();
domain.on('error', (err) => {
    console.error('Asynchronous error while executing script.', err.stack);
});
domain.run(() => {
    try {
        vm.run(script, filename);
    } catch (err) {
        console.error('Synchronous error while executing script.', err.stack);
    }
});

All 8 comments

You can handle asynchronous errors like this:

process.on('uncaughtException', (err) => {
    console.log(err);
})

Keep in mind that this catches all exceptions from both inside and outside of the VM.

Thx. Yes, it partially helped me. BTW, is there any way to distinguish if error in 'uncaughtException' is related to a VM (and possibly, which of them) or not?

Unfortunately not at the moment. I have an idea how to implement this but it will take some time.

I'm wrapping vm.run() with domain.run() and it seems to work. I don't know if it has any side effects though..

let domain = Domain.create();
domain.on('error', (err) => {
    console.error('Asynchronous error while executing script.', err.stack);
});
domain.run(() => {
    try {
        vm.run(script, filename);
    } catch (err) {
        console.error('Synchronous error while executing script.', err.stack);
    }
});

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

@alsterg The method seems to lose effectiveness..

@patriksimek Could you please tell me if you forgot about this?

Confirming @ImSingee, method unfortunately does not work anymore.
Is there any update on how to handle async errors?

Any updates on this???

Was this page helpful?
0 / 5 - 0 ratings

Related issues

wojpawlik picture wojpawlik  ·  4Comments

KonradLinkowski picture KonradLinkowski  ·  10Comments

somebody1234 picture somebody1234  ·  4Comments

keyosk picture keyosk  ·  64Comments

patriksimek picture patriksimek  ·  5Comments