2016-02-26 27 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