3
 app.factory('$exceptionHandler', function() {
      return function(exception, cause) {
        exception.message += ' (caused by "' + cause + '")';
        throw exception;
      };
  });

$exceptionHandler書き込みtrythrowブロックなしで使用して、angularJs ですべての例外をグローバルに処理することは可能ですか?

try-catch私が望むのは、 var のようなステートメントのブロックを書き忘れてもa=1/0、上記のコードで処理したいということです。

4

1 に答える 1

4

はい、AngularJS でのグローバル エラー処理は可能です。基本的に、構成時に、デフォルトの動作を変更するために$exceptionHandlerサービスをデコレートします。コードは次のようになります。

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
          };
        }]);
  }]);

注:場合によっては$delegate、元のサービス インスタンスであるため、 も呼び出す必要があります。この場合、$exceptionHandler の codeを見ると、これだけが行われます。

$log.error.apply($log, arguments);

出典: John Papa の Angular Styleguide

于 2016-02-26T08:48:05.820 に答える