JSONP Ajax error handling

I’m using the Twitter API for a project. The results it returns are.. awkward. In particular you often get errors for legitimate requests, but if you try the exact same request again a few seconds later it will work. Presumably their internal caching / timeouts.

Anyway, I need a good way to do error handling of AJAX calls in Javascript. But because I’m doing cross-origin stuff (and Twitter doesn’t set the CORS header) I’m stuck using JSONP. And JSONP error handling sucks, presumably because the crazy <script> eval hack that makes JSONP work doesn’t let Javascript code handle errors.

Options:

  1. jQuery Timeouts. Since version 1.5, jQuery will throw a timeout after N seconds if the JSONP call did not succeed. This gives you limited error notification, albeit asynchronously.
  2. suppress_response_codes. This is a special hack to the Twitter API to always have them return HTTP 200 OK, even on errors, and let you figure out the error in the body. Using this lets you bypass the browser’s own handling of, say, a 400 error and let your Javascript code handle it. Ie when I’m rate limited I get a “400 (Bad Request)” from the API which Chrome intercepts and all I see is a timeout. Presumably with this Twitter API setting, I’ll get a 200 reply immediately that contains info on the error I can parse.
  3. Try Zepto. Their JSONP code is different from jQuery and a preliminary look suggests it might have a better error handling strategy. Seems unlikely, but worth a look?

JSONP is such a horrible hack. I wish Twitter would just set the CORS header and I could use a proper JSON call with XmlHttpRequest with proper error handling. I could do that myself if I proxy the traffic on my server, but then it’s my bandwidth and my IP address being rate limited.