Line number of SyntaxError in Node.js

Viewed 10817

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 SyntaxError or something else. instaceof doesn't work (update - I can use e.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).

4 Answers
Related