Throwing an Error in jQuery’s Deferred object

Now updated for jQuery 1.8+

The easiest way to tackle this is to run the response of $.ajax through .then to filter based on success or failure of the data.

$.ajax()
    .then(function (response) {
        return $.Deferred(function (deferred) {
            var problem = hasError(response);

            if (problem) {
                return deferred.reject(problem)
            }

            deferred.resolve(response);
        }).promise();
    });

You could then return this new promise to whatever calling code would consume this:

var request = function () {
    return $.ajax()
        .then(function (response) {
            return $.Deferred(function (deferred) {
                var problem = hasError(response);

                if (problem) {
                    return deferred.reject(problem)
                }

                deferred.resolve(response);
            }).promise();
        });
};

request()
    .done(function (response) {
        // handle success
    })
    .fail(function (problem) {
        // handle failure
    });

Leave a Comment