views:

195

answers:

4

In JavaScript I have a var str = ".a long string that contains many lines..." In case of exception that caused by eval(str);

I had like to catch it and print the the line number that caused the exception. (the line internal to str..)

Is it possible?

EDIT As part of the Alligator project (http://github.com/mrohad/Alligator), an application server for JavaScript, I am reading files from the disk and eval() anything that is nested to a scriplet( < ? ? > )

I am running this script outside a browser, using NodeJS (on top of V8).

+1  A: 

This solves your problem?

try {
    eval(str);
} catch (e) {
    console.log(e.lineNumber)
}
Topera
I am getting undefined for e.lineNumber...
MrOhad
@MrOhad, the `lineNumber` property on Error objects is *non-standard*, it will work only on Mozilla implementations, but I'm afraid that it will return you the line number where you invoked `eval`, not the actual line number inside the evaluated text.
CMS
Works in Firefox, but not other browsers. In Chrome/Iron, you can get the row number close to the end of `e.stack`.
Gert G
e.stack doesn't return undefined yet it does return the line of the eval and not the line internal to the eval string
MrOhad
Can you say what does e contain?
AndreyKo
Sure:message: aasas is not defined; stack: ReferenceError: aasas is not defined at eval at serverSideScripting (/home/vadmin/Alligator/lib/jssp.js:262:4)...;type: not_defined; arguments: aasas; name: ReferenceError;
MrOhad
e is an exception. In firefox it has many properties, like: fileName, lineNumber, message, name and stack. Why I get -1?
Topera
it's not me..(the down-voter), sorry.
MrOhad
+1  A: 

1) Run:

var javascript_offset;
try {
  undefined_function();
} catch(ex1) {
  javascript_offset = ex1.lineNumber;
}
try {
  YOUR_STRING_WITH_JS
} catch (ex2) {
  var line_that_caused_it = ex2.lineNumber - javascript_offset -2;
  HANDLE_THE_EXCEPTION_HERE
}
AndreyKo
I am running this script outside a browser, using NodeJS (on top of V8)
MrOhad
+1  A: 

Try adding the try/catch to the string instead of around the eval:

var code = 'try{\nvar c = thisFuncIsNotDefined();\n}catch(e){alert(e.lineNumber);}';
Steve Brewer
I thought it's even better than my solution, but I have tested it and it doesn't work, same stack as if the try{} catch{} wasn't part of the eval
MrOhad
+2  A: 

I found a solution which is pretty inefficient, yet I only use it when debug_mode==1 so it's not that bad..

I write the eval_str to a file, I "import that file, and invoke it inside a try{}catch{} and I parse the error line from the stack trace...

In my specific case, this is how the code looks like:

var errFileContent = "exports.run = "+evalStringAsAFunction+";";
fs.writeFile('/home/vadmin/Alligator/lib/debugging.js', errFileContent, function (err) {
    var debug = require('./debugging');
    try{
         debug.run(args...);
    }
    catch(er){
         log.debug(parseg(er));
    }
});
MrOhad