Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
78
rated 0 times [  83] [ 5]  / answers: 1 / hits: 16057  / 10 Years ago, sun, april 27, 2014, 12:00:00

In the following code, an exception is caught by the catch function of the $q promise:



// Fiddle - http://jsfiddle.net/EFpn8/6/
f1().then(function(data) {
console.log(success 1: +data)
return f2();
})
.then(function(data) {console.log(success 2: +data)})
.catch(function(data) {console.log(error: +data)});

function f1() {
var deferred = $q.defer();
// An exception thrown here is not caught in catch
// throw err;
deferred.resolve(done f1);
return deferred.promise;
}

function f2() {
var deferred = $q.defer();
// An exception thrown here is handled properly
throw err;
deferred.resolve(done f2);
return deferred.promise;
}


However when I look in the console log output I see the following:



enter



The exception was caught in Angular, but was also caught by the error handling of the browser. This behavior does reproduce with Q library.



Is it a bug? How can I truly catch an exception with $q?


More From » angularjs

 Answers
35

Fixed with AngularJS version 1.6



The reasoning for this behavior was that an uncaught error is different than a regular rejection, as
it can be caused by a programming error, for example. In practice, this turned out to be confusing
or undesirable for users, since neither native promises nor any other popular promise library
distinguishes thrown errors from regular rejections.
(Note: While this behavior does not go against the Promises/A+ spec, it is not prescribed either.)




$q:



Due to e13eea, an error thrown from a promise's onFulfilled or onRejection handlers is treated exactly the same as a regular rejection. Previously, it would also be passed to the $exceptionHandler() (in addition to rejecting the promise with the error as reason).



The new behavior applies to all services/controllers/filters etc that rely on $q (including built-in services, such as $http and $route). For example, $http's transformRequest/Response functions or a route's redirectTo function as well as functions specified in a route's resolve object, will no longer result in a call to $exceptionHandler() if they throw an error. Other than that, everything will continue to behave in the same way; i.e. the promises will be rejected, route transition will be cancelled, $routeChangeError events will be broadcasted etc.



-- AngularJS Developer Guide - Migrating from V1.5 to V1.6 - $q



[#71282] Thursday, April 24, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jazminkyrap

Total Points: 631
Total Questions: 89
Total Answers: 109

Location: Finland
Member since Fri, Oct 21, 2022
2 Years ago
;