繁体   English   中英

角JS:$ exceptionHandler没有尝试或抛出块?

[英]Angular JS : $exceptionHandler without try or throw block?

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

是否可以使用$exceptionHandler在angularJs中全局处理所有$exceptionHandler而无需编写trythrow块?

我想要的是即使我忘记为var a=1/0 1/0之类的语句编写try-catch块,我也想在上面的代码中处理它。

是的,可以在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 Styleguide

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM