Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

325
Views
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?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report

0

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

over 4 years ago · Santiago Trujillo Report

0

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.') };
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!