5

This is a brief outline of my code:

$.getJSON(json_url, function(data) {
    // application logic
}).error(function() {
    console.log("error");
});

The problem is that when the server returns a 404 error, it does not appear to be handled as there is no console.log() saying error, but there is a GET request failure with a code of 404 (Not Found) showing up in the console.

I am using jQuery 1.9.0.

Is there some simple error I am making?

ixchi
  • 2,349
  • 2
  • 26
  • 23
  • 1
    Try `.fail` instead of `.error`... the latter is deprecated (though that does not mean that it won't work). – Felix Kling Jan 17 '13 at 01:19
  • That also does not seem to work. Is there another method to try instead of getJSON for JSONP? Also, the jQuery docs say error on the getJSON page, why would that work, but not what the docs say work? – ixchi Jan 17 '13 at 01:24
  • Are you sure it's a 404 and not a JSON syntax error, which will fail silently? – Beetroot-Beetroot Jan 17 '13 at 01:35
  • It's JSONP, would that make a difference? With the callback function it's not valid JSON, but without it it's valid. I'm calling the Twitter API, if that makes a difference. – ixchi Jan 17 '13 at 01:37
  • 1
    As I understand, Twitter will respond with JSONP if a `callback="..."` function is present. Similarly, jQuery will handle the request as JSONP if `callback="..."` is present. I think the problem with a 404 is that servers can return HTML (a page containing a marked up error message). [This question](http://stackoverflow.com/questions/2493974/how-to-callback-a-function-on-404-in-json-ajax-request-with-jquery) asks the same question - you may be able to glean something from the answers (though unfortunately none is accepted). – Beetroot-Beetroot Jan 17 '13 at 02:05

1 Answers1

3

Due to the nature of JSONP requests, the error callback is not called for those.

From the docs:

When data is retrieved from remote servers (which is only possible using the script or jsonp data types), the error callbacks and global events will never be fired.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Okay, thanks. I never saw that note before. I'll just use the `$.ajax()` function instead. – ixchi Jan 17 '13 at 02:01
  • `$.getJSON` just calls `$.ajax` internally. If you can only access the API via JSONP then there is no way to make jQuery call the error callbacks. – Felix Kling Jan 17 '13 at 02:03
  • I have successfully made `$.ajax` run my error handler when the JSONP link 404s. I used [this answer](http://stackoverflow.com/a/5121811/1289450) to figure it out. – ixchi Jan 17 '13 at 02:18
  • 2
    Ah... ok. That's only because of the timeout though. You still won't know *what* the error actually is. You might find this plugin useful: https://github.com/jaubourg/jquery-jsonp. – Felix Kling Jan 17 '13 at 02:19
  • Thank you very much! That plugin saves a ton of time, and works perfectly. – ixchi Jan 17 '13 at 02:36