I have a class that I am loading in to the a global vm context and I am executing a script within the shared context. Works fine when things are correct. But if I accidentally forget to define a variable when using one of the setters, I get a reference error and the application crashes.
const document = new document('users');
document.fetch('0939e8bde2f74213a0bd75bea8d82f8b').then(() => {
document.setValue('middleName', bob); //bob is not defined
});
setValue
is never executed. I have tried several ways to capture the error and no luck. I have tried added try/catch to the wrappedScriptContent
. I have tried a try/catch within the async function. For now I have settle on the process.on
but that doesn’t give me any details.
Here is my executeScript method as it stands.
async executeScript(script) {
const context = vm.createContext({...this.sharedContext});
const wrappedScriptContent = `
(async function() {
${script}
})();`;
try {
const scriptObject = new vm.Script(wrappedScriptContent);
scriptObject.runInContext(context, { timeout: 5000, displayErrors: true });
return { success: true, result: '' };
} catch (error) {
console.error(`Error executing script: ${error}`);
}
}
Is there a way to handle errors, known or not known? I am looking for a way to handle errors gracefully and try to provide detailed logging.