Excepción de Javascript eval () - número de línea


En JavaScript tengo un var str = ".a long string that contains many lines..." En caso de excepción causada por eval(str);

Tenía gusto de cogerlo e imprimir el el número de línea que causó la excepción. (la línea interna a str..)

Es posible?

EDITAR Como parte del proyecto Alligator ( http://github.com/mrohad/Alligator ), un servidor de aplicaciones para JavaScript, estoy leyendo archivos del disco y eval () cualquier cosa que esté anidada en un scriplet ( )

Estoy ejecutando esto script fuera de un navegador, usando NodeJS (encima de V8).

Author: DuduAlul, 2010-08-15

4 answers

Intente agregar el try / catch a la cadena en lugar de alrededor de la eval:

var code = 'try{\nvar c = thisFuncIsNotDefined();\n}catch(e){alert(e.lineNumber);}';
 6
Author: Steve Brewer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-15 20:53:04

1) Ejecutar:

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
}
 3
Author: AndreyKo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-15 20:30:53

Encontré una solución que es bastante ineficiente, pero solo la uso cuando debug_mode==1, por lo que no es tan mala..

Escribo eval_str en un archivo, "importo ese archivo, lo invoco dentro de un try{}catch{} y analizo la línea de error del seguimiento de la pila...

En mi caso específico, así es como se ve el código:

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));
    }
});
 3
Author: DuduAlul,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-15 21:07:42

¿Esto resuelve tu problema?

try {
    eval(str);
} catch (e) {
    console.log(e.lineNumber)
}
 0
Author: Topera,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-15 20:19:45