aWebDeveloper
aWebDeveloper

Reputation: 38332

Fix Uncaught ReferenceError

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

Upvotes: 5

Views: 1872

Answers (2)

Paul
Paul

Reputation: 705

try{
 if(Debug){
    debug(data,code)
 }
}
catch{
// swallow or do whatever you want
}

Upvotes: 0

user2437417
user2437417

Reputation:

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.

Upvotes: 2

Related Questions