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

$exceptionHandler是否可以在不写入try或阻塞的情况下在 angularJs 中全局处理所有异常throw

我想要的是即使我忘记为try-catchvar 之类的语句编写块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 的代码,它只这样做:

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

资料来源: John Papa 的 Angular 风格指南

于 2016-02-26T08:48:05.820 回答