Best way to prevent Javascript from failing.

Javascript is a great flexible language but has a major flaw with portability. I call it the “1 Hit Combo super punchy epic fail” error, aka Error Object. The Error object has 6 beautiful children that everyone hates to see. Their names are EvalError, RangeError, ReferenceError, SyntaxError, TypeError and URIError, and your task a good professional Frontend programmer is to prevent those 7 object from never stepping foot onto your website. So here are some simple tips to assist you in your struggle.


Solution 1:
First off, you should check your code to make sure that you’re not the one causing the errors message.
So check your code with code analysis tools like JSlint, console2 (a firefox addon ) or Google’s Closure inspector.

Solution 2:
If possible you could also wrap your error prone code in try or catch blocks.
Try and Catch works as follow.

Sends an error message to the browser and further Javascript from executing.

var obj = [];
obj[0] = globalVar;    //ERROR!

Send the error message to the catch block and let’s the developer decide what to do.

try{
    var obj = [];
    obj[0] = globalVar;
}
catch( err ){
    alert( "Error Message: " + err.message ); //You should log the error instead of alert it.
}

Solution 3:
For a page that requires javascript, you can load that page with a iframe. With a iframe or frame, even if your main page halts due to an error, your javascript in your iframe will continue to run.

For something else that might help, check out ADSAFE (protection against 3rd party scripts).

References:
MDN Doc Center: Error
Stackoverflow : Is it possible to “sandbox” arbitrary JavaScript to only operate on one div and not the whole document?

Larry Battle

I love to program, and discover new tech. Check out my stackoverflow and github accounts.

Share
Published by
Larry Battle

Recent Posts

What really is Data Science? Told by a Data Scientist

What REALLY is Data Science? Told by a Data Scientist - By Joma Tech

7 years ago

Video: How Water Towers Work

How Water Towers Work - Practical Engineering

7 years ago

Dev Tip: Simple tips to improve code reviews

Writing perfect code is a challenging process. That's where code reviews come in to help…

7 years ago

Video: How AI will change the 3d industry

"The Next Leap: How A.I. will change the 3D industry - Andrew Price - Blender"

7 years ago

Best Software Presentation for 2018

"Captain Disillusion: World's Greatest Blenderer - Live at the Blender Conference 2018 - CaptainDisillusion"

7 years ago

Dev Video: A Few Linux Shell Tips

My 5 Favorite Linux Shell Tricks for SPEEEEEED (and efficiency) - By tutoriaLinux > What's…

7 years ago