简体   繁体   中英

Module Exceptions in Angularjs and $exceptionHandler

In the documentation of Angular 1 for $exceptionHandler it says:

Any uncaught exception in angular expressions is delegated to this service.

https://code.angularjs.org/1.3.20/docs/api/ng/service/ $exceptionHandler

Yet when I get a module initialisation error ( Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to: ... ) it does not seem to get logged via the $exceptionHandler.

I want to be able to log these Errors to Sentry via Raven and am having trouble finding a solution to this.

This is an example of what i am trying to achieve:

 // Main App module angular.module('app', ['app.welcome', 'app.contact']) .factory('$exceptionHandler', [function() { return function myExceptionHandler(exception, cause) { // why does the module initialisation error not get caught here..? console.log("[ERROR] ", exception.message); }; }]); // a module I forgot to load.. // app.module('app.contact', []); // another sub module angular. module('app.welcome', []) .controller('ExampleController', ['$scope', '$window', function($scope, $window) { $scope.test = function() { $window.alert('test'); }; }]); 
 <!doctype html> <html lang="en" ng-app="app"> <head> <meta charset="utf-8"> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.min.js"></script> <script src="script.js"></script> </head> <body ng-controller="ExampleController"> <button ng-click="test()">Test</button> </body> </html> 

Here is a snippet which raise an error because $q is not injected, do whatever you want in custom exception handler.

 angular.module('app', []); angular. module('app') .controller('ExampleController', ['$scope', function($scope) { $scope.test = function() { $q.when("foo"); }; }]) .factory('$exceptionHandler', [function() { return function myExceptionHandler(exception, cause) { console.log("[ERROR] ", exception.message); }; }]); 
 <!doctype html> <html lang="en" ng-app="app"> <head> <meta charset="utf-8"> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.min.js"></script> <script src="script.js"></script> </head> <body ng-controller="ExampleController"> <button ng-click="test()">Raise Error</button> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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