1

I have a JavaScript script that is using the jquery post command to log into a server and obtain a token. I've wrapped my code in a try block with a catch block that looks like this:

catch (error)
{
  alert(error.message); 
}

My code runs fine, but to test it thoroughly, I intentionally changed the protocol so that the url looks like this:

"htt://some.domain:8080/jsonrpc"

My code does not catch the error and display the alert. Rather, the Chrome console shows the following error:

XMLHttpRequest cannot load htt://some.domain:8080/jsonrpc. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

I would expect some kind of malformed url exception instead of the error in the console.

The results of other intentional errors such as incorrect password result in exceptions that are caught.

Thanks

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Steve Murphy
  • 431
  • 2
  • 7
  • 17

1 Answers1

3

Because Ajax is asynchronous. The error occurs outside the try/catch block.

This class of error can be detected in XMLHttpRequest by the status changing to 0. (This status code also covers a few other error states though, so you can't be precise).

The error handler you can pass to jQuery ajax will fire when the status is 0.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Yes, that's what happens. But OP seems also to ask *why* it is not an exception, as it could be detected synchronously like malformed `send` arguments or invalid HTTP methods to `open`? – Bergi Apr 28 '15 at 14:27
  • Thanks everyone. Looks like I will have to check the status code – Steve Murphy Apr 28 '15 at 16:35
  • @ brso05: I tried posting the full code, but it's too long and the StackOverflow page won't accept it. – Steve Murphy Apr 28 '15 at 16:46