-
-
Save thbar/1209593 to your computer and use it in GitHub Desktop.
rescueFrom for jQuery AJAX requests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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