3
 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.

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.