27

Suppose I'm calling 3 javascript (jquery) files like this:

<script type="text/javascript" src="js/file1.js"></script>
<script type="text/javascript" src="js/file2.js"></script>
<script type="text/javascript" src="js/file3.js"></script>

On file2.js there are script errors (or something with a function goes wrong): for example, it says "function does not exist". Because there is an error in file2.js, scripts in file3.js are not executed.

Is there is a way to make sure scripts in file3.js are still executed? Or, is it possible to bypass or ignore the error on file2.js?

STerliakov
  • 4,983
  • 3
  • 15
  • 37
Fredy
  • 2,840
  • 6
  • 29
  • 40
  • 3
    try/catch, but really you should fix the underlying problem. – Matt Ball Apr 19 '13 at 03:10
  • if you know there are errors, and you refuse to fix em, why include the file at all? chances are a majority of that file won't run properly anyways because of the errors – aug Apr 19 '13 at 03:12
  • Possible duplicate of [Ignore javascript syntax errors in a page and continue executing the script](http://stackoverflow.com/questions/12219154/ignore-javascript-syntax-errors-in-a-page-and-continue-executing-the-script) – Ciro Santilli OurBigBook.com Sep 18 '16 at 23:17

6 Answers6

39

You can use a try catch block around the code with the error

try{

//code that causes an error

}catch(e){

functionToHandleError(e);
}
//continue from here

But you should only do that if the error is a known condition/unavoidable problem with an external library or only happens on bad user input. You shouldn't use it to allow the program to keep running at all costs.

Some ways to avoid errors

  • check that functions exist before calling them
  • check that an object exists before referencing its properties
  • if user input is involved, validate the input to check that it's the expected type/range/etc
  • if this is a loading order problem consider reordering your scripts, or if this is a larger application using a dependency management system like requireJS
  • if objects are undefined after an asynchronous request, remember that code does not wait on an async request and it will not be defined until afterwards. Code dealing with the provided values should be done in a callback function or using deffereds/promises.
  • if you're referencing dom elements, consider starting your JS code from within a function that runs when the DOM is loaded such as jQuery's document.ready or the native window.onload.
  • if javascript variables are declared without the var keyword, or are attached to a global object, they can be modified in places other than they are declared. Javascript also doesn't have block scope. Make sure you know all the places your variables are being modified, and try to limit the scope of your variables when possible. Especially avoid using too many global variables to hold state, as it can be difficult to know the current state without many null/type checks.

Some ways to handle errors

  • If its an expected problem (IE if the input may be empty and requires different handling), ideally check it with an if statement beforehand. If you don't want to do that, you can use try/catch to cast the input, ask for new input, or act on the input given as approperiate.

  • if its an unexpected problem (IE you don't know whats going on) a catch block can be a good place to output diagnostic information during development. IE, don't just catch it and let it fail silently, output a message to let you or other developers know where it failed, and then use your favorite browser's web developer tools to inspect the values at the time, figure out what happened, and add handling for that case to fix it.

What not to do

  • put the try/catch in, and then just let the program keep on running. If the code that isn't running correctly is unnecessary, get rid of it. If it is necessary and isn't working correctly, fix it.

  • use try catches as your input validation (IE if the function is null it will throw an exception and I'll catch it, then I know the function is null). Whenever possible, check for any expected errors. Try/catches should handle "exceptions" when the behavior is unusual and you need to go down an alternative code path or alert the user that something is wrong.

Ben McCormick
  • 25,260
  • 12
  • 52
  • 71
  • It doesn't work in async calls. I'm scratching my head for a long time to catch exception thrown by a function which was called by an async call in react :( – Ankur Parihar Aug 27 '21 at 15:08
17

When you don't have time to debug try this:

function stoperror() {
   return true;
}

Call it:

window.onerror = stoperror;

The functionality is very simple: create a function that always returns true, and then whenever an error occurs, call this function (returning true and suppressing the error).

trincot
  • 317,000
  • 35
  • 244
  • 286
Jamil Bashir
  • 307
  • 3
  • 10
  • 1
    It doesn't work with `Uncaught TypeError: Cannot read property 'remove' of undefined`, Here's my code: `var rows = document.getElementsByTagName("tr"); for (i=0; i < rows.length; i++){ rows[i].childNodes[0].remove(); }` – Shayan Sep 11 '19 at 10:11
4

you can use try and catch statements.And check for null by using != null condition

try{


}catch(e){

}
Ben McCormick
  • 25,260
  • 12
  • 52
  • 71
PSR
  • 39,804
  • 41
  • 111
  • 151
3

Wrap the call that results in an error in a try...catch block:

try {
   callNonExistentMethod();
}
catch (e) {
   //Handle the error if you wish.
}
Justin Helgerson
  • 24,900
  • 17
  • 97
  • 124
3

you can save yourself from "function is undefined" by using this

//Simple function that will tell if the function is defined or not
function is_function(func) {
    return typeof window[func] !== 'undefined' && $.isFunction(window[func]);
}

//usage

if (is_function("myFunction") {
    alert("myFunction defined");
} else {
    alert("myFunction not defined");
}
trincot
  • 317,000
  • 35
  • 244
  • 286
Muhammad Tahir
  • 2,351
  • 29
  • 25
1

I would suggest adding proper null checks around objects(including functions) before assuming they exist,so that the code will fail gracefully.

Here are some ideas: Javascript check if function exists

Community
  • 1
  • 1
TGH
  • 38,769
  • 12
  • 102
  • 135