Search code examples
javascriptshellerror-handlingxmlhttprequestphantomjs

How to Handle XMLHttpRequest Exception 101 Error in PhantomJS?


I am a newer for JavaScript and also for PhantomJS. When I run myfile.js (bears for loops) with command phantomjs myfile.js, it occasionally(but definitely will) gives out

NETWORK_ERR: XMLHttpRequest Exception 101: A network error occurred in synchronous requests.

Every time this error occurs, I have to terminate this process(using Ctrl+C in my terminal), and then use bash command below to continue my job

$ some bash command to clean the job done before error occurs
$ phantomjs myfile.js

It is really depressing especially I have a large for loop to do. So, I am wondering whether there is some way to automatically execute these lines whenever it gives out

NETWORK_ERR: XMLHttpRequest Exception 101 

In my rough thoughts, I may have some error handling code within myfile.js, or embed phantomjs myfile.js within a shell script file and catch the error it occurs.

Could anybody teach me how to do this?

Here is my main PhantomJS code:

    // myfile.js
    var request = new XMLHttpRequest();
    var myURLs = ["url1","url2", ... ]; // this array contains more than 10k URLs
    for (i=0; i<myURLs.length; i++) {
      request.open('GET', myURLs[i], false); // synchronous request
      request.setRequestHeader("HEADERKEY","HEADERVALUE");
      request.send();
      if (request.status === 200) {
        console.log(request.responseText);
      } else {
        console.log("Error Code: " + request.status);
        phantom.exit();
      }
    }
    phantom.exit();

For private reason, I can't share the URLs within the myURLs array. Pretty sorry for that, but I still ask for help if you got some idea from my code.


Solution

  • Sigh, I gotta to answer my own question here.

    PhantomJS provides a global error handler called onError. It is extremely useful when phantomjs throws out errors.

    You can find detailed information here: http://phantomjs.org/api/phantom/handler/on-error.html