2016-02-26 40 views
2
app.factory('$exceptionHandler', function() { 
     return function(exception, cause) { 
     exception.message += ' (caused by "' + cause + '")'; 
     throw exception; 
     }; 
    }); 

是否有可能在全球范围内处理所有的异常使用$exceptionHandler angularJs无需编写trythrow块?

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

回答

3

是的,AngularJS中的全局错误处理是可能的。基本上,在配置时,你decorate$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's code,它不仅会:

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

来源:John Papa's Angular Styleguide

相关问题