How to catch NetworkError in JavaScript?

Synthead picture Synthead · Nov 27, 2013 · Viewed 46.7k times · Source

In Chrome's JavaScript console, if I run this:

var that = new XMLHttpRequest();
that.open('GET', 'http://this_is_a_bad_url.com', false);
that.send();

I get an intentionally expected error:

NetworkError: A network error occurred.

I want to catch this, so I use:

var that = new XMLHttpRequest();
that.open('GET', 'http://this_is_a_bad_url.com', false);
try {
  that.send();
} catch(exception) {
  if(exception instanceof NetworkError) {
    console.log('There was a network error.');
  }
}

However, I get an error about NetworkError not being defined:

ReferenceError: NetworkError is not defined

How can I catch NetworkError?

Answer

Rob M. picture Rob M. · Nov 27, 2013

I think what you meant was:

if(exception.name == 'NetworkError'){
   console.log('There was a network error.');
}

I don't believe the Error is an instance of NetworkError, but thrown in this manner:

throw {
   name: 'NetworkError',
   message: 'A network error occurred.'
   // etc...
}