Skip to content

Instantly share code, notes, and snippets.

@thbar
Forked from assaf/gist:1207141
Created September 11, 2011 13:38
Show Gist options
  • Save thbar/1209593 to your computer and use it in GitHub Desktop.
Save thbar/1209593 to your computer and use it in GitHub Desktop.
rescueFrom for jQuery AJAX requests
rescue_from = {}
# Associate status code with an HTTP status code. First argument is the status
# code, second argument is a function that accepts the XHR object. For example:
# $.rescueFrom 404, (xhr)-> alert("Oh no, page not found!")
$.rescueFrom = (status, fn)->
rescue_from[status] = fn
# Default handling for unsuccessulf HTTP status code. Finds and calls most
# appropriate handler based on the HTTP status code (see `$.rescueFrom`).
#
# This method is called on all AJAX requests that do not define an error
# handler. If your request needs a specific error handler, you can delegate
# here for default handling.
$.xhrError = (xhr)->
if fn = rescue_from[xhr.status]
fn xhr
else if xhr.status != 0
switch new String(xhr.getResponseHeader("Content-Type")).split(";")[0]
when "text/plain", null
message = xhr.responseText
when "application/json"
response = JSON.parse(xhr.responseText)
message = response.errors[0] if response.errors
# Twitter search throws this shit half the time... `parsererror`
unless xhr.statusText and xhr.statusText == "parsererror"
$.notice.error message || "Uh oh, there was a problem"
# Catch AJAX errors and delegate to `app.xhrError`.
$.ajaxSetup error: (xhr)-> $.xhrError xhr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment