简体   繁体   中英

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).

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?
  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.

  1. You can't : js scripts are loaded at once.
  2. The only way to prevent it is to design your code correctly, using try/catch and to write and run tests

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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