jabuj
jabuj

Reputation: 3649

JS: getting error line number inside `new Function(...)`

In my application I parse some user input and then run it as Javascipt code using (new Function(...))(). If the input is incorrect, this throws an exception. What I need is a way to get the line number where the exception happened in the parsed string that had been provided to new Function(). Is it possible?

Upvotes: 1

Views: 731

Answers (2)

nullpointer7
nullpointer7

Reputation: 11

formatError(err)
{
    const regex = new RegExp("<anonymous>:[0-9]*:[0-9]*");
    const anynomError = err.stack.match(regex);

    if (anynomError.length > 0)
    {
        const lineNumber = anynomError[0].split(":")[1] - 2;
        return `Error on line ${lineNumber}: ${err}`;
    }

    return err;
}

Upvotes: 0

Amardeep Bhowmick
Amardeep Bhowmick

Reputation: 16908

For this we need to write a logic to capture the stacktrace from the error object and find out where exactly the anonymous function has indicated the error has been thrown.

The line number where the error is thrown in Chrome is indicated as <anonymous>:5:17, where as in Firefox it is Function:5:17

try{
 (new Function(`var hello = 10;
                const world = 20;
                let foo = 'bar';
                xyz; //simulating error here
 `))();
}catch(err){
   let line = err.stack.split("\n").find(e => e.includes("<anonymous>:") || e.includes("Function:"));
   let lineIndex = (line.includes("<anonymous>:") && line.indexOf("<anonymous>:") + "<anonymous>:".length) ||  (line.includes("Function:") && line.indexOf("Function:") + "Function:".length);
   console.log(+line.substring(lineIndex, lineIndex + 1) - 2);
}

Upvotes: 2

Related Questions