How to continue javascript execution when an error occurs

I use the WP native function wp_enqueue_script() for all my script loading in both WP front and back-end so it can handle duplicated calls to the same script and so on.

One of the issues is that other programmers don’t use this function and load their scripts directly from their code, which causes jQuery or jQuery-UI to be loaded twice, leading to a bunch of errors.

Read More

The other issue is that code not owned by me triggers an error and stops the execution of JavaScript beyond this point.

In short:

A Javascript error occurs in code not owned by me.
My code doesn’t execute due to that error.
I want my code to bypass that error and still execute.
Is there a way to handle these issues?

Related posts

Leave a Reply

2 comments

  1. function ShieldAgainThirdPartyErrors($) {
        // Code you want protect here...
    }
    
    // First shot.
    // If no error happened, when DOMContentLoaded is triggered, this code is executed.
    jQuery(ShieldAgainThirdPartyErrors);
    
    // Backup shot.
    // If third party script throw or provoke an unhandled exception, the above function 
    // call could never be executed, so, lets catch the exception and execute the code.
    window.onerror = function () {
    
        ShieldAgainThirdPartyErrors(jQuery);
    
        return true;
    }
    

    If you want pull the trigger of your gun twice just when necessary 😉 set a flag to signal that the first shot was successful and avoid the backup shot, I think that under some circumstances your first shot could be executed even third party code get in trouble and trigger the second shot.

  2. Not at all recommended but you can use:

    try {  
      //Some code likely to throw an error  
    } catch (err) {}
    

    This will allow anything after to continue running though you should generally catch the error too. The only case when I would not catch the error is when working with arrays and doing somearray[i-1] where the i-1 would be less than 0. This is only because it is cleaner than using conditionals to prevent it.