I have some code that uses vm module and runInNewContext function and executes dynamically generated JavaScript code. Basically a safer option of eval.
The code (variable code) can possibly contain syntax errors, so I would like to catch them and print some useful information.
try {
vm.runInNewContext(code, sandbox, filename);
}
catch (e) {
if (e instanceof SyntaxError) { // always false
console.log(e.toString()); // "SyntaxError: Unexpected token ||" for example
console.log(e.line); // how to get the line number?
}
}
I'd like to print the number of the line with the syntax error, but I have two problems:
- I don't know how to recognize whether the exception is
SyntaxErroror something else.instaceofdoesn't work (update - I can usee.name === "SyntaxError"). - Even if I was able to recognize it, how could I get the line number? Is it possible?
Thanks in advance.
Update: I can get some information from e.stack - however, the topmost call in the stack trace is runInNewContext (with its line number), but I still can't find the line number inside code, which caused the exception (SyntaxError).