Reputation: 1687
app.factory('$exceptionHandler', function() {
return function(exception, cause) {
exception.message += ' (caused by "' + cause + '")';
throw exception;
};
});
Is it possible to handle all the exception globally in angularJs using $exceptionHandler
without writing try
or throw
block?
What I want is even if I forget to write the try-catch
block for the statements like var a=1/0
, I want to handle it in the above code.
Upvotes: 3
Views: 2047
Reputation: 7072
Yes, global error handling in AngularJS is possible. Basically, at config time, you decorate the $exceptionHandler service in order to modify its default behaviour. The code would look something like this:
angular
.module('global-exception-handler', [])
.config(['$provide', function($provide) {
$provide
.decorator('$exceptionHandler', ['$delegate', function($delegate) {
return function(exception, cause) {
$delegate(exception, cause);
// Do something here
};
}]);
}]);
Note: in some cases, you should also call $delegate
as it's the original service instance. In this case, taking a look at $exceptionHandler's code, it only does this:
$log.error.apply($log, arguments);
Source: John Papa's Angular Styleguide
Upvotes: 4