Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching XMLHttpRequest cross-domain errors

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?

like image 985
kpozin Avatar asked Feb 16 '11 15:02

kpozin


3 Answers

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.

like image 97
monsur Avatar answered Nov 19 '22 21:11

monsur


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

like image 31
Vikram Pudi Avatar answered Nov 19 '22 22:11

Vikram Pudi


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.') };
like image 3
Felipe Brahm Avatar answered Nov 19 '22 20:11

Felipe Brahm