Skip to content

Commit

Permalink
Ability to identify timeout errors
Browse files Browse the repository at this point in the history
Allows Q.timeout message to be a custom Error object or sets error.code == 'ETIMEDOUT'

Fixes kriskowal#513
  • Loading branch information
kornelski committed Apr 8, 2014
1 parent cdb9dc9 commit 814b45f
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
14 changes: 9 additions & 5 deletions q.js
Original file line number Diff line number Diff line change
Expand Up @@ -1670,18 +1670,22 @@ Promise.prototype.done = function (fulfilled, rejected, progress) {
* some milliseconds time out.
* @param {Any*} promise
* @param {Number} milliseconds timeout
* @param {String} custom error message (optional)
* @param {Any*} custom error message or Error object (optional)
* @returns a promise for the resolution of the given promise if it is
* fulfilled before the timeout, otherwise rejected.
*/
Q.timeout = function (object, ms, message) {
return Q(object).timeout(ms, message);
Q.timeout = function (object, ms, error) {
return Q(object).timeout(ms, error);
};

Promise.prototype.timeout = function (ms, message) {
Promise.prototype.timeout = function (ms, error) {
var deferred = defer();
var timeoutId = setTimeout(function () {
deferred.reject(new Error(message || "Timed out after " + ms + " ms"));
if (!error || "string" === typeof error) {
error = new Error(error || "Timed out after " + ms + " ms");
error.code = "ETIMEDOUT";
}
deferred.reject(error);
}, ms);

this.then(function (value) {
Expand Down
16 changes: 16 additions & 0 deletions spec/q-spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -1634,10 +1634,26 @@ describe("timeout", function () {
},
function (error) {
expect(/custom/i.test(error.message)).toBe(true);
expect(error.code).toBe("ETIMEDOUT");
}
);
});

it("should reject with a custom timeout error if the promise is too slow and Error object was provided", function () {
var customError = new Error("custom");
customError.isCustom = true;
return Q.delay(100)
.timeout(10, customError)
.then(
function () {
expect(true).toBe(false);
},
function (error) {
expect(/custom/i.test(error.message)).toBe(true);
expect(error.isCustom).toBe(true);
}
);
});

});

Expand Down

0 comments on commit 814b45f

Please sign in to comment.