Fix Uncaught ReferenceError

Fix Uncaught ReferenceError

本文关键字:ReferenceError Uncaught Fix      更新时间:2023-09-26

修复 Uncaught ReferenceError 的一般解决方案是什么?

我正在创建一个函数,以确保调试代码进入生产。但是在某些情况下,变量不存在,但调试代码仍然存在。在这种情况下,它不应该停止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

应该避免在生产环境中运行调试代码。

最好是有一个构建过程来删除它,但是一个简单的标志来包装你的调试调用也可以。

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

这将比到处测试未声明的变量更干净。

毕竟,调试的一部分就是查找对未声明变量的意外访问。因此,在调试时,我们应该希望看到这些ReferenceErrors,以便我们可以修复它们。

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