I feel like I am going a little crazy, but Angular appears to throw an error for a promise even if I have a catch
defined. It throws the error to the console, then allows the catch
to run.
Here is a super-simple fiddle
The test code:
$q.when(1)
.then(function() {
throw new Error("test");
}).catch(function(error) {
console.log('error caught', error);
});
The resulting console
(dirty liar!)
Here is a fiddle showing what I expect to happen: the catch
is raised, and no other error is logged to the console. Did I fail to configure something, or does Angular implement a broken promise spec?
catch " around the executor automatically catches the error and turns it into rejected promise. This happens not only in the executor function, but in its handlers as well. If we throw inside a . then handler, that means a rejected promise, so the control jumps to the nearest error handler.
Promises can be executed by calling the then() and catch() methods. The then() method takes two callback functions as parameters and is invoked when a promise is either resolved or rejected. The catch() method takes one callback function and is invoked when an error occurs.
You cannot use try-catch statements to handle exceptions thrown asynchronously, as the function has "returned" before any exception is thrown. You should instead use the promise. then and promise. catch methods, which represent the asynchronous equivalent of the try-catch statement.
To create a promise in Angular we just need to use 'new Promise(function)' syntax. The promise constructor takes function as a parameter and that inner function takes resolve and reject as a params.
angular by default logs all errors to console.
angular also provides a way to override this behavior. $exceptionHandler
is a global service that is given a chance to process any exceptions ($http, errors during $digest, etc).
If you add this piece of code:
myApp.factory('$exceptionHandler', function() {
return function(exception, cause) {
exception.message += ' (caused by "' + cause + '")';
//throw exception;
};
});
Then all errors would just stop further logging. Would process catch() handlers though. Updated fiddle: http://jsfiddle.net/5jjx5rn3/
UPDATE:
As pointed by dnc253
in the comments, there's a better way if you intend to actually override an angularjs service. Even not being the focus of this question, it's better to know that simply declaring a service with the same name, in whatever module, the service is fully replaced (last-in wins). If one wants to add functionality around the original service, a decorator is the right choice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With