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).
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 $@ .
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.
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.
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.
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);}';
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With