Jquery ajax custom error handler
I am writing a backbone js web application on top of a JSON server that returns JSON responses to J Submit BOM format .
Here are some examples of this format:
GET / posts
{
"status": "success",
"data": {
"posts" [
{"id": 1, "title": "A blog post"},
{"id": 2, "title": "another blog post"}
]
}
}
POST / posts
{
"status": "fail",
"data": {
"title": "required"
}
}
By default, the "error" event in $ .ajax is triggered on HTTP codes, but since the JSend specification format does not use HTTP codes at all, I need to rewrite the $ .ajax error handler.
How it works by default (http codes):
$.ajax({
error: function() {
// Do your job here.
},
success: function() {
// Do your job here.
}
});
How can I rewrite the $ .ajax error handler that is triggered when the body is parsed and if the "status" property is "fail" or "error"?
+3
source to share
2 answers
As unintuitive as it sounds, you'll have to put it in a function success
. Just check the value yourself:
$.ajax({
error: function() {
// Handle http codes here
},
success: function(data) {
if(data.status == "fail"){
// Handle failure here
} else {
// success, do your thing
}
}
});
+4
source to share
To keep things DRY, you can use something like this:
function JSendHandler(success, fail) {
if (typeof success !== 'function' || typeof fail !== 'function') {
throw 'Please, provide valid handlers!';
}
this.success = success;
this.fail = fail;
}
JSendHandler.prototype.getHandler = function () {
return function (result) {
if (result.status === 'fail') {
this.fail.call(this, arguments);
} else {
this.success.call(this, arguments);
}
}
};
function success() { console.log('Success'); }
function error() { console.log('Fail!'); }
var handler = new JSendHandler(success, error);
$.ajax({
error: error,
success: handler.getHandler()
});
+1
source to share