Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 431
DuduAlul Avatar asked Aug 15 '10 19:08

DuduAlul


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 we should not use eval in JavaScript?

eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension.

What is EvalError JavaScript?

The EvalError object indicates an error regarding the global eval() function. This exception is not thrown by JavaScript anymore, however the EvalError object remains for compatibility.

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.


2 Answers

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);}'; 
like image 156
Steve Brewer Avatar answered Sep 25 '22 02:09

Steve Brewer


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 } 
like image 39
AndreyKo Avatar answered Sep 23 '22 02:09

AndreyKo