Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tracing the source line of an error in a Javascript eval

Tags:

I'm building something that includes javascripts on the fly asynchronously, which works, but I'm looking to improve upon the error detection (so all the errors don't just appear to come from some line near the AJAX call that pulls them down.

If I'm using eval to evaluate a multiline javascript file, is there any way to trace which line an error occurs on?

By keeping references to the variables I need when including, I have no problem determining which file the errors occurs in. My problem is determining which line the error occurs in.

Example:

try {
  eval("var valid_statement = 7; \n invalid_statement())))");
} catch(e) {
  var err = new Error();
  err.message = 'Error in Evald Script: ' + e.message;
  err.lineNumber = ???
  throw err;
}

How can I tell that the error occurred in the second line there? Specifically I'm interested in doing this in Firefox.

I know that error objects have e.stack in Mozilla browsers, but the output doesn't seem to take into account newlines properly.

like image 794
Jamie Wong Avatar asked Aug 19 '10 22:08

Jamie Wong


People also ask

How do you catch eval errors?

Catching exceptions To catch an exception, use eval() . eval() parses, compiles, and evaluates a block of code at compile time and catches any exceptions that are raised at runtime. The exception is placed in the global variable $@ .

Why eval () is the evil?

eval() is evil if running on the server using input submitted by a client that was not created by the developer or that was not sanitized by the developer. eval() is not evil if running on the client, even if using unsanitized input crafted by the client.

What is $$ eval?

page.$$eval(selector, pageFunction[, ...args]) This method runs Array. from(document. querySelectorAll(selector)) within the page and passes it as the first argument to pageFunction . If pageFunction returns a Promise, then page. $$eval would wait for the promise to resolve and return its value.

Why we should not use eval in JavaScript?

Malicious code : invoking eval can crash a computer. For example: if you use eval server-side and a mischievous user decides to use an infinite loop as their username. Terribly slow : the JavaScript language is designed to use the full gamut of JavaScript types (numbers, functions, objects, etc)… Not just strings!


1 Answers

  • The line number in an evaled script starts from the one the eval is on.
  • An error object has a line number of the line it was created on.

So something like...

try {
  eval('var valid_statement = 7; \n invalid_statement())))');
} catch(e) {
  var err = e.constructor('Error in Evaled Script: ' + e.message);
  // +3 because `err` has the line number of the `eval` line plus two.
  err.lineNumber = e.lineNumber - err.lineNumber + 3;
  throw err;
}
like image 131
matyr Avatar answered Oct 16 '22 05:10

matyr