Skip to content

Commit

Permalink
feat($q): report promises with non rejection callback
Browse files Browse the repository at this point in the history
Rejected promises that do not have a callback to handle the rejection report
this to $exceptionHandler so they can be logged to the console.

BREAKING CHANGE

Tests that depend on specific order or number of messages in $exceptionHandler
will need to handle rejected promises report.

Closes: angular#13653
Closes: angular#7992
  • Loading branch information
lgalfaso committed Jan 2, 2016
1 parent 986647a commit 8c2419d
Show file tree
Hide file tree
Showing 12 changed files with 139 additions and 38 deletions.
2 changes: 1 addition & 1 deletion src/ng/compile.js
Original file line number Diff line number Diff line change
Expand Up @@ -2494,7 +2494,7 @@ function $CompileProvider($provide, $$sanitizeUriProvider) {
childBoundTranscludeFn);
}
linkQueue = null;
});
}).then(noop, noop);

return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
var childBoundTranscludeFn = boundTranscludeFn;
Expand Down
2 changes: 2 additions & 0 deletions src/ng/interval.js
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,8 @@ function $IntervalProvider() {
*/
interval.cancel = function(promise) {
if (promise && promise.$$intervalId in intervals) {
// Interval cancels should not report as unhandled promise.
intervals[promise.$$intervalId].promise.then(noop, noop);
intervals[promise.$$intervalId].reject('canceled');
$window.clearInterval(promise.$$intervalId);
delete intervals[promise.$$intervalId];
Expand Down
69 changes: 55 additions & 14 deletions src/ng/q.js
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,8 @@ function $$QProvider() {
*/
function qFactory(nextTick, exceptionHandler) {
var $qMinErr = minErr('$q', TypeError);
var queueSize = 0;
var checkQueue = [];

/**
* @ngdoc method
Expand Down Expand Up @@ -307,28 +309,67 @@ function qFactory(nextTick, exceptionHandler) {
pending = state.pending;
state.processScheduled = false;
state.pending = undefined;
for (var i = 0, ii = pending.length; i < ii; ++i) {
deferred = pending[i][0];
fn = pending[i][state.status];
try {
if (isFunction(fn)) {
deferred.resolve(fn(state.value));
} else if (state.status === 1) {
deferred.resolve(state.value);
} else {
deferred.reject(state.value);
try {
for (var i = 0, ii = pending.length; i < ii; ++i) {
state.pur = true;
deferred = pending[i][0];
fn = pending[i][state.status];
try {
if (isFunction(fn)) {
deferred.resolve(fn(state.value));
} else if (state.status === 1) {
deferred.resolve(state.value);
} else {
deferred.reject(state.value);
}
} catch (e) {
deferred.reject(e);
exceptionHandler(e);
}
} catch (e) {
deferred.reject(e);
exceptionHandler(e);
}
} finally {
--queueSize;
if (queueSize === 0) {
nextTick(processChecksFn());
}
}
}

function processChecks() {
while (!queueSize && checkQueue.length) {
var toCheck = checkQueue.shift();
if (!toCheck.pur) {
toCheck.pur = true;
var errorMessage = 'Possibly unhandled rejection: ';
try {
errorMessage += toJson(toCheck.value);
} catch (e) {
errorMessage += '[recursive value]';
}
exceptionHandler(errorMessage);
}
}
}

function processChecksFn() {
return function() { processChecks(); };
}

function processQueueFn(state) {
return function() { processQueue(state); };
}

function scheduleProcessQueue(state) {
if (!state.pending && state.status === 2 && !state.pur) {
if (queueSize === 0 && checkQueue.length === 0) {
nextTick(processChecksFn());
}
checkQueue.push(state);
}
if (state.processScheduled || !state.pending) return;
state.processScheduled = true;
nextTick(function() { processQueue(state); });
++queueSize;
nextTick(processQueueFn(state));
}

function Deferred() {
Expand Down
2 changes: 2 additions & 0 deletions src/ng/timeout.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,8 @@ function $TimeoutProvider() {
*/
timeout.cancel = function(promise) {
if (promise && promise.$$timeoutId in deferreds) {
// Timeout cancels should not report an unhandled promise.
deferreds[promise.$$timeoutId].promise.then(noop, noop);
deferreds[promise.$$timeoutId].reject('canceled');
delete deferreds[promise.$$timeoutId];
return $browser.defer.cancel(promise.$$timeoutId);
Expand Down
3 changes: 2 additions & 1 deletion src/ngMock/angular-mocks.js
Original file line number Diff line number Diff line change
Expand Up @@ -445,7 +445,7 @@ angular.mock.$IntervalProvider = function() {
promise = deferred.promise;

count = (angular.isDefined(count)) ? count : 0;
promise.then(null, null, (!hasParams) ? fn : function() {
promise.then(null, function() {}, (!hasParams) ? fn : function() {
fn.apply(null, args);
});

Expand Down Expand Up @@ -505,6 +505,7 @@ angular.mock.$IntervalProvider = function() {
});

if (angular.isDefined(fnIndex)) {
repeatFns[fnIndex].deferred.promise.then(undefined, function() {});
repeatFns[fnIndex].deferred.reject('canceled');
repeatFns.splice(fnIndex, 1);
return true;
Expand Down
3 changes: 2 additions & 1 deletion src/ngResource/resource.js
Original file line number Diff line number Diff line change
Expand Up @@ -702,12 +702,13 @@ angular.module('ngResource', ['ng']).
return $q.reject(response);
});

promise.finally(function() {
promise = promise.finally(function(response) {
value.$resolved = true;
if (!isInstanceCall && cancellable) {
value.$cancelRequest = angular.noop;
timeoutDeferred = httpConfig.timeout = null;
}
return response;
});

promise = promise.then(
Expand Down
2 changes: 1 addition & 1 deletion test/ng/animateRunnerSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ describe("$$AnimateRunner", function() {
var animationComplete = false;
runner.finally(function() {
animationComplete = true;
});
}).then(noop, noop);
runner[method]();
$rootScope.$digest();
expect(animationComplete).toBe(true);
Expand Down
2 changes: 1 addition & 1 deletion test/ng/compileSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -1870,7 +1870,7 @@ describe('$compile', function() {
});
});

inject(function($compile, $templateCache, $rootScope, $exceptionHandler) {
inject(function($compile, $templateCache, $rootScope, $exceptionHandler, $timeout) {
// no root element
$templateCache.put('template.html', 'dada');
$compile('<p template></p>');
Expand Down
6 changes: 3 additions & 3 deletions test/ng/httpSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -1031,7 +1031,7 @@ describe('$http', function() {

it('should $apply after error callback', function() {
$httpBackend.when('GET').respond(404);
$http({method: 'GET', url: '/some'});
$http({method: 'GET', url: '/some'}).then(noop, noop);
$httpBackend.flush();
expect($rootScope.$apply).toHaveBeenCalledOnce();
});
Expand Down Expand Up @@ -1432,7 +1432,7 @@ describe('$http', function() {

function doFirstCacheRequest(method, respStatus, headers) {
$httpBackend.expect(method || 'GET', '/url').respond(respStatus || 200, 'content', headers);
$http({method: method || 'GET', url: '/url', cache: cache});
$http({method: method || 'GET', url: '/url', cache: cache}).then(noop, noop);
$httpBackend.flush();
}

Expand Down Expand Up @@ -1640,7 +1640,7 @@ describe('$http', function() {

it('should preserve config object when rejecting from pending cache', function() {
$httpBackend.expect('GET', '/url').respond(404, 'content');
$http({method: 'GET', url: '/url', cache: cache, headers: {foo: 'bar'}});
$http({method: 'GET', url: '/url', cache: cache, headers: {foo: 'bar'}}).then(noop, noop);

$http({method: 'GET', url: '/url', cache: cache, headers: {foo: 'baz'}}).catch(callback);
$httpBackend.flush();
Expand Down
72 changes: 61 additions & 11 deletions test/ng/qSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
*/

describe('q', function() {
var q, defer, deferred, promise, log;
var q, defer, deferred, promise, log, exceptionHandlerCalls;

// The following private functions are used to help with logging for testing invocation of the
// promise callbacks.
Expand Down Expand Up @@ -181,12 +181,23 @@ describe('q', function() {
};


function exceptionHandler(reason) {
exceptionHandlerCalls.push(reason);
}


function exceptionHandlerStr() {
return exceptionHandlerCalls.join('; ');
}


beforeEach(function() {
q = qFactory(mockNextTick.nextTick, noop),
q = qFactory(mockNextTick.nextTick, exceptionHandler),
defer = q.defer;
deferred = defer();
promise = deferred.promise;
log = [];
exceptionHandlerCalls = [];
mockNextTick.queue = [];
});

Expand Down Expand Up @@ -1586,6 +1597,8 @@ describe('q', function() {
var rejectedPromise = q.reject('rejected');
expect(rejectedPromise['finally']).not.toBeUndefined();
expect(rejectedPromise['catch']).not.toBeUndefined();
rejectedPromise.then(noop, noop);
mockNextTick.flush();
});
});

Expand Down Expand Up @@ -1995,15 +2008,15 @@ describe('q', function() {
it('should log exceptions thrown in a success callback and reject the derived promise',
function() {
var success1 = success(1, 'oops', true);
promise.then(success1).then(success(2), error(2));
promise.then(success1).then(success(2), error(2)).then(noop, noop);
syncResolve(deferred, 'done');
expect(logStr()).toBe('success1(done)->throw(oops); error2(oops)->reject(oops)');
expect(mockExceptionLogger.log).toEqual(['oops']);
});


it('should NOT log exceptions when a success callback returns rejected promise', function() {
promise.then(success(1, q.reject('rejected'))).then(success(2), error(2));
promise.then(success(1, q.reject('rejected'))).then(success(2), error(2)).then(noop, noop);
syncResolve(deferred, 'done');
expect(logStr()).toBe('success1(done)->{}; error2(rejected)->reject(rejected)');
expect(mockExceptionLogger.log).toEqual([]);
Expand All @@ -2012,15 +2025,15 @@ describe('q', function() {

it('should log exceptions thrown in a errback and reject the derived promise', function() {
var error1 = error(1, 'oops', true);
promise.then(null, error1).then(success(2), error(2));
promise.then(null, error1).then(success(2), error(2)).then(noop, noop);
syncReject(deferred, 'nope');
expect(logStr()).toBe('error1(nope)->throw(oops); error2(oops)->reject(oops)');
expect(mockExceptionLogger.log).toEqual(['oops']);
});


it('should NOT log exceptions when an errback returns a rejected promise', function() {
promise.then(null, error(1, q.reject('rejected'))).then(success(2), error(2));
promise.then(null, error(1, q.reject('rejected'))).then(success(2), error(2)).then(noop, noop);
syncReject(deferred, 'nope');
expect(logStr()).toBe('error1(nope)->{}; error2(rejected)->reject(rejected)');
expect(mockExceptionLogger.log).toEqual([]);
Expand All @@ -2029,7 +2042,7 @@ describe('q', function() {

it('should log exceptions throw in a progressack and stop propagation, but shoud NOT reject ' +
'the promise', function() {
promise.then(success(), error(), progress(1, 'failed', true)).then(null, error(1), progress(2));
promise.then(success(), error(), progress(1, 'failed', true)).then(null, error(1), progress(2)).then(noop, noop);
syncNotify(deferred, '10%');
expect(logStr()).toBe('progress1(10%)->throw(failed)');
expect(mockExceptionLogger.log).toEqual(['failed']);
Expand All @@ -2045,15 +2058,15 @@ describe('q', function() {
it('should log exceptions thrown in a success callback and reject the derived promise',
function() {
var success1 = success(1, 'oops', true);
q.when('hi', success1, error()).then(success(), error(2));
q.when('hi', success1, error()).then(success(), error(2)).then(noop, noop);
mockNextTick.flush();
expect(logStr()).toBe('success1(hi)->throw(oops); error2(oops)->reject(oops)');
expect(mockExceptionLogger.log).toEqual(['oops']);
});


it('should NOT log exceptions when a success callback returns rejected promise', function() {
q.when('hi', success(1, q.reject('rejected'))).then(success(2), error(2));
q.when('hi', success(1, q.reject('rejected'))).then(success(2), error(2)).then(noop, noop);
mockNextTick.flush();
expect(logStr()).toBe('success1(hi)->{}; error2(rejected)->reject(rejected)');
expect(mockExceptionLogger.log).toEqual([]);
Expand All @@ -2062,7 +2075,7 @@ describe('q', function() {

it('should log exceptions thrown in a errback and reject the derived promise', function() {
var error1 = error(1, 'oops', true);
q.when(q.reject('sorry'), success(), error1).then(success(), error(2));
q.when(q.reject('sorry'), success(), error1).then(success(), error(2)).then(noop, noop);
mockNextTick.flush();
expect(logStr()).toBe('error1(sorry)->throw(oops); error2(oops)->reject(oops)');
expect(mockExceptionLogger.log).toEqual(['oops']);
Expand All @@ -2071,7 +2084,7 @@ describe('q', function() {

it('should NOT log exceptions when an errback returns a rejected promise', function() {
q.when(q.reject('sorry'), success(), error(1, q.reject('rejected'))).
then(success(2), error(2));
then(success(2), error(2)).then(noop, noop);
mockNextTick.flush();
expect(logStr()).toBe('error1(sorry)->{}; error2(rejected)->reject(rejected)');
expect(mockExceptionLogger.log).toEqual([]);
Expand All @@ -2080,6 +2093,43 @@ describe('q', function() {
});


describe('when exceptionHandler is called', function() {
it('should log an unhandled rejected promise', function() {
var defer = q.defer();
defer.reject('foo');
mockNextTick.flush();
expect(exceptionHandlerStr()).toBe('Possibly unhandled rejection: "foo"');
});


it('should log a handled rejected promise on a promise without rejection callbacks', function() {
var defer = q.defer();
defer.promise.then(noop);
defer.reject('foo');
mockNextTick.flush();
expect(exceptionHandlerStr()).toBe('Possibly unhandled rejection: "foo"');
});


it('should not log a handled rejected promise', function() {
var defer = q.defer();
defer.promise.then(noop, noop);
defer.reject('foo');
mockNextTick.flush();
expect(exceptionHandlerStr()).toBe('');
});


it('should not log a handled rejected promise that is handled in a future tick', function() {
var defer = q.defer();
defer.promise.then(noop, noop);
defer.resolve(q.reject('foo'));
mockNextTick.flush();
expect(exceptionHandlerStr()).toBe('');
});
});


describe('when exceptionHandler rethrows exceptions, ', function() {
var originalLogExceptions, deferred, errorSpy, exceptionExceptionSpy;

Expand Down
4 changes: 2 additions & 2 deletions test/ng/timeoutSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ describe('$timeout', function() {
expect($exceptionHandler.errors).toEqual([]);

$timeout.flush();
expect($exceptionHandler.errors).toEqual(["Test Error"]);
expect($exceptionHandler.errors).toEqual(["Test Error", 'Possibly unhandled rejection: "Test Error"']);
}));


Expand Down Expand Up @@ -238,7 +238,7 @@ describe('$timeout', function() {
$timeout(task2);
promise3 = $timeout(task3, 333);
promise4 = $timeout(333);
promise3.then(task4);
promise3.then(task4, noop);

$timeout.cancel(promise1);
$timeout.cancel(promise3);
Expand Down
Loading

0 comments on commit 8c2419d

Please sign in to comment.