Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fix Uncaught ReferenceError

Tags:

javascript

What is a general solution to fix Uncaught ReferenceError.

I am creating a function to ensure debugging code goes into production. But there may be cases where a variable doesn't exist but the debugging code still exists. In such case it shouldn't halts the js.

function debug(data, type){
    if(type == 'alert' && mode !== 'production'){
      alert(data);
    }
    else if(type == 'halt' && mode !== 'production'){
      debugger;
    }
    else{
      console.debug(data);
    }
}

debug(xyz) //xyz doesn't exists
like image 697
aWebDeveloper Avatar asked Nov 03 '22 21:11

aWebDeveloper


1 Answers

You should avoid running debug code in production.

Best is to have a build process that removes it, but a simple flag that wraps your debug calls works too.

window.DEBUG = true;

//...

if (DEBUG) {
    debug(xyz) //xyz doesn't exist... and it won't matter when DEBUG === false
}

This will be cleaner than testing for undeclared variables all over the place.

After all, part of debugging is finding accidental access to undeclared variables. So when debugging, we should want to see those ReferenceErrors so we can fix them.

like image 99
user2437417 Avatar answered Nov 12 '22 12:11

user2437417