DuduAlul
DuduAlul

Reputation: 6390

Javascript eval() Exception - line number

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).

Upvotes: 27

Views: 16798

Answers (5)

user16784826
user16784826

Reputation: 1

replaceErrors(key, value) {
    if (value instanceof Error) {
      var error = {};
      Object.
        getOwnPropertyNames(value).
        forEach(function (key) {
          error[key] = value[key];
        });
      return error;
    }
    return value;
  }
const errorStr = JSON.stringify(error.stack, this.replaceErrors);
const regexp = 'your reg';
          let isHasLineNum = regexp.exec(errorStr);
          let lineNum
          if (isHasLineNum) {
            lineNum = isHasLineNum[0];
          }

Upvotes: 0

DuduAlul
DuduAlul

Reputation: 6390

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));
    }
});

Upvotes: 3

Steve Brewer
Steve Brewer

Reputation: 2100

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);}';

Upvotes: 4

AndreyKo
AndreyKo

Reputation: 909

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
}

Upvotes: 3

Topera
Topera

Reputation: 12389

This solves your problem?

try {
    eval(str);
} catch (e) {
    console.log(e.lineNumber)
}

Upvotes: -2

Related Questions