views:

33

answers:

1

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.

+1  A: 
  • 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;
}
matyr
Beware that `e.lineNumber` is a non-standard JavaScript feature.
casablanca
"Specifically I'm interested in doing this in **Firefox**"
matyr
Perfect! That did _exactly_ what I wanted. It's kind of unfortunate that it relies on hardcoded differences between line numbers, but at least it works. The major problem with that is that it won't work if I run a minifier on the script. Regardless, thank you very much.
Jamie Wong