Search code examples
javascriptangularjsangularjs-module

How to handle AngularJS config block errors


Hi folks I am new to angular js. I have a module 'ngApp' which depends on a module 'ng-main'. I want to handle errors and exceptions that might be thrown in a config block of 'ng-main' module. I have created a new module 'ng-error' and made 'ngApp' dependent on this module to handle errors and exceptions but it's kind of not catching it.

index.html

<script type="text/javascript">
  angular.module('ngApp', ['ng-error', 'ng-main']);
</script> 

ngErrors.js

angular.module('ng-error',[])
 .config(function($provide) {
    $provide.factory('$exceptionHandler', function($injector) {
        return function (exception, cause) {
            console.log(exception);

            // display error message 

        };
    });
});

ngMain.js

angular.module('ng-main', ['ng-test'])
.config(function(){
  // code with error
}); 

If any errors occurs in this config block it totally fails but I want to manually handle those. Any thoughts or comments on my code?


Solution

  • Okay, Tried below code and worked. Manually overridden angular bootstrap process and wrapping that code inside try{} catch {} block to handle errors in config block

    something like this:

      <script type="text/javascript">
        angular.module('ngApp', ['ng-error', 'ng-main']);
    
       angular.element(document).ready(function() {
         try {
            angular.bootstrap(document, ['ngApp']);
         } catch(e) {
           //handle errors
         }
      });
      </script>