Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular JS : $exceptionHandler without try or throw block?

 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.

like image 939
shreyansh Avatar asked Jun 16 '26 22:06

shreyansh


1 Answers

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

like image 163
Cosmin Ababei Avatar answered Jun 19 '26 12:06

Cosmin Ababei



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!