29

Is there any way to catch an error caused by Access-Control-Allow-Origin when making a request? I'm using jQuery, and the handler set in .ajaxError() never gets called because the request is never made to begin with.

Is there any workaround?

1

3 Answers 3

24

For CORS requests, the XmlHttpRequest's onError handler should fire. If you have access to the raw XmlHttpRequest object, try setting an event handler like:

function createCORSRequest(method, url){
  var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr){
    xhr.open(method, url, true);
  } else if (typeof XDomainRequest != "undefined"){
    xhr = new XDomainRequest();
    xhr.open(method, url);
  } else {
    xhr = null;
  }
  return xhr;
}

var url = 'YOUR URL HERE';
var xhr = createCORSRequest('GET', url);
xhr.onerror = function() { alert('error'); };
xhr.onload = function() { alert('success'); };
xhr.send();

Note a few things:

  • On CORS requests, the browser's console.log will display an error message. However, that error message is not available to your JavaScript code (I think this is done for security reasons, I asked this question once before: Is it possible to trap CORS errors?).

  • The xhr.status and xhr.statusText aren't set in the onError handler, so you don't really have any useful information as to why the CORS request failed. You only know that it failed.

Sign up to request clarification or add additional context in comments.

3 Comments

Ah, but how do you distinguish errors caused by CORS restrictions from other unspecified AJAX errors? There seems to be nothing discernible in the readyState, status, and statusText properties of an XMLHttpRequest object that failed due to CORS.
I don't think that's possible, see this question: stackoverflow.com/questions/4844643/…
XDomainRequest is deprecated
8

It is possible to get error status like so:

xhr.onerror = function(e) {
    alert("Error Status: " + e.target.status);
};

Source: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

1 Comment

-1 I don't see anything like that in your reference, and in fact there should be no status code in onError. onError only fires on network failures, and if you have a status code that means a response was successfully received.
3

Set a handler for onerror and you'll be able to catch the cross-domain exceptions. I don't know why the onerror event is fired for exceptions and not the error event, but I just tested it and it worked.

req = $.get('http://www.example.com');
req.onerror = function() { alert('An exception occurred.') };

1 Comment

thats how js works,req.onerror = function () {..} is equivalent to req.addEventListener('error', function () {..})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.