6

I'm using jQuery.getJSON() on a URL (different domain) which may not exist. Is there a way for me to catch the error "Failed to load resource"? It seems that try/catch doesn't work because of the asynchronous nature of this call.

I can't use jQuery.ajax()'s "error:" either. From the documetation:

Note: This handler is not called for cross-domain script and JSONP requests.

Matthew Simoneau
  • 6,199
  • 6
  • 35
  • 46
  • Please confirm: The error probably is not *thrown* per se, but simply appears in the console (only when you open the console). – Ates Goral Feb 07 '11 at 18:38
  • 2
    I am seeing it when the Chrome console is open, or equivalent in other browsers. With the developer tools closed, this error is silent. It's shaping up that a) there's no way to block this and b) I shouldn't worry about it? – Matthew Simoneau Feb 07 '11 at 19:08

4 Answers4

11

If you have an idea of the worst case delay of a successful result returning from the remote service, you can use a timeout mechanism to determine if there was an error or not.

var cbSuccess = false;
$.ajax({
   url: 'http://example.com/.../service.php?callback=?',
   type: 'get',
   dataType: 'json',
   success: function(data) {
              cbSuccess = true;
            }
});
setTimeout(function(){ 
        if(!cbSuccess) { alert("failed"); } 
    }, 2000); // assuming 2sec is the max wait time for results
Joy Dutta
  • 3,416
  • 1
  • 19
  • 19
  • Thanks for your reply. This will still throw the "Failed to load resource" error, which is the thing I'm trying to stop. – Matthew Simoneau Feb 07 '11 at 18:31
  • 4
    @Matthew Simoneau: That error gets *logged*, not *thrown*. You cannot prevent that error from being logged in the console. – Ates Goral Feb 07 '11 at 18:36
  • Matthew, the error is thrown by the browser/firebug layer, so I am not sure if you can catch and stop that kind of stuff. Maybe some way to connect with firebug js ? – Joy Dutta Feb 07 '11 at 18:38
1

This works:

j.ajaxSetup({
    "error":function(xhr, ajaxOptions, thrownError) {   

    console.log(thrownError);                           
}});
Guillermo
  • 11
  • 1
  • 1
    Are you sure? Cross-domain / JSONP calls don't use XHR, they use script injection. (At least in this case where CORS is not considered.) – hippietrail Dec 18 '11 at 16:44
-2

Deferred objects (new in jQuery 1.5) sound like exactly what you're looking for:

jQuery.Deferred, introduced in version 1.5, is a chainable utility object that can register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function.

http://api.jquery.com/category/deferred-object/

EDIT:

The following code works fine for me:

function jsonError(){
    $("#test").text("error");
}

$.getJSON("json.php",function(data){
    $("#test").text(data.a);
}).fail(jsonError);

json.php looks like this:

print '{"a":"1"}';

The error function fires for me if the path to json.php is incorrect or if the JSON is malformed. For example:

print '{xxx"a":"1"}';
Bryan Downing
  • 15,194
  • 3
  • 39
  • 60
  • 2
    Not quite. Defferreds are a generic mechanism for synchronizing the outcome of async operations. The OPs problem is with detecting if a JSONP request fails. – Ates Goral Feb 07 '11 at 18:37
  • This looked promising. I'm unfamiliar with this and might be doing this wrong, but this doesn't seem to work: $.getJSON("http://www.bogus.com/&callback=?").fail(function() {}); – Matthew Simoneau Feb 07 '11 at 18:41
  • 1
    Bryan, thanks taking a look at this. I'm dealing with a cross-site JSONP request to a URL which may not exist. This technique still throws this error. I'm coming around to believing that this is impossible to stop but I can safely ignore it because it only shows up in browser's developer mode. – Matthew Simoneau Feb 08 '11 at 00:08
  • I didn't realize that you were working with JSONP (despite all the references :/). Yeah, that console error appears to be unbeatable, but I wouldn't worry about it either. However, in my tests it does seem that jQuery 1.5 fires the error handler for failed JSONP requests. Check out this post as well: http://stackoverflow.com/questions/1002367/jquery-ajax-jsonp-ignores-a-timeout-and-doesnt-fire-the-error-event – Bryan Downing Feb 08 '11 at 01:45
-6

What your complaining about is a client-side error saying that you tried to download a resource from the server.

This is build into the browser and it allows your browser to tell the client or the developers that the downloading of a resource from the internet failed. This has nothing to do with JavaScript and is a more low level error thrown on the HTTP that is caught by the browser.

If you want any hope of catching it your going to need to drop 3rd party ajax libraries and deal with the XMLHTTPRequest object on a much lower level, even then I doubt you can do anything about it.

Basically when you see this error then find out what object your trying to get that doesn't exist or couldn't be accessed. Then either stop accessing it or make it accessible.

Raynos
  • 166,823
  • 56
  • 351
  • 396
  • 5
    First two paragraphs are great. Third is completely wrong. JSONP is a different animal. But with regular .ajax stuff, you can use the deferred object to handle errors far more elegantly than messing directly with XMLHTTPRequest. – Ryan Florence Aug 09 '11 at 22:40
  • @rpflo meh XMLHttpRequest is more elegant then `.ajax` and deferreds. However show me an example where you can catch this "error" using jQuery. – Raynos Jan 16 '12 at 18:20