简体   繁体   English

javascript错误停止运行时执行

[英]javascript error stops runtime execution

We had a situation today where 1 small error (on line 500) in our JS library file (3000+ lines long) caused a runtime error (calling a method on an undefined object). 今天我们遇到的情况是,JS库文件中的1个小错误(第500行)(长3000+行)导致运行时错误(在未定义对象上调用方法)。

The error stoped further execution of all other code in the library file causing our site to not work properly. 该错误停止了库文件中所有其他代码的进一步执行,导致我们的网站无法正常运行。

My question is: 我的问题是:

  1. Since JS is single threaded, will splitting up our code into multiple files and scopes help resolve issues like that in the future? 由于JS是单线程的,将来将我们的代码拆分为多个文件和范围将有助于解决类似的问题吗?
  2. If we don't split it up, how can we prevent this from happening. 如果我们不进行拆分,那么如何防止这种情况发生。

thx, 谢谢,

Simple solution would be to check if the object exists before attempting to call the method on it. 一个简单的解决方案是在尝试调用该对象之前检查对象是否存在。

if ( myObject && myObject.myObjectFunction )
    myObject.myFunction();
else
    return false;

If the object exists and the object has the function you want to call then it'll call the function, otherwise it'll return false and not attempt to call the function, thus avoiding the error entirely. 如果对象存在并且该对象具有您要调用的函数,则它将调用该函数,否则它将返回false并且不尝试调用该函数,从而完全避免了该错误。

  1. You can't : js scripts are loaded at once. 您不能:js脚本立即加载。
  2. The only way to prevent it is to design your code correctly, using try/catch and to write and run tests 防止它的唯一方法是正确地设计代码,使用try / catch以及编写和运行测试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM