Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch a referenceError in js

I have a textarea where user can enter javascript code which upon press of the button would be passed to eval().

I am having trouble catching the referenceError for cases when a user enters something like this:

var myName = Maria;

instead of

var myName = "Maria";

Thank you for you time!

like image 367
jacobdo Avatar asked Sep 12 '15 09:09

jacobdo


People also ask

How do you handle uncaught ReferenceError?

Answer: Execute Code after jQuery Library has Loaded The most common reason behind the error "Uncaught ReferenceError: $ is not defined" is executing the jQuery code before the jQuery library file has loaded. Therefore make sure that you're executing the jQuery code only after jQuery library file has finished loading.

What is a ReferenceError in JavaScript?

The ReferenceError object represents an error when a variable that doesn't exist (or hasn't yet been initialized) in the current scope is referenced. ReferenceError is a serializable object, so it can be cloned with structuredClone() or copied between Workers using postMessage() .

How do I fix reference error in JavaScript?

Reference errors in Javascript are mainly thrown when an attempt is made to reference a variable that does not exist or is out of scope. Therefore, in the majority of cases, a ReferenceError can be fixed by making sure that the referenced variable is defined correctly and is being called in the correct scope.

What is try catch in JavaScript?

JavaScript try and catchThe try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block. The JavaScript statements try and catch come in pairs: try {


1 Answers

Try putting a try/catch block around the eval() call. Like this:

try {
    eval(userInput);
} catch (e) {
    // do something
}

(Note that passing user input to eval() is NOT something you should do on a real site, for security reasons.)

like image 175
ecraig12345 Avatar answered Sep 23 '22 00:09

ecraig12345