Exploring Error Handling in AngularJS and How to Use $exceptionHandler

When it comes to the documentation of Angular 1 for $exceptionHandler, it states:

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

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

However, I have noticed that when encountering a module initialization error (

Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to: ...
), it doesn't seem to be recorded through the $exceptionHandler.

I am looking to log these errors to Sentry via Raven but struggling to find a solution.

Below is an example of what I am attempting to achieve:

// Main App module
angular.module('app', ['app.welcome', 'app.contact'])
    .factory('$exceptionHandler', [function() {
        return function myExceptionHandler(exception, cause) {
           // Why isn't the module initialization error caught here..?
           console.log("[ERROR] ", exception.message);
        };
     }]);

// A module that was not loaded..
// 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>

Answer №1

Encountering an error is inevitable with this code snippet, as $q has not been injected. Feel free to customize the exception handler according to your needs.

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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I'm struggling to make the jquery parentsUntil function work properly

Would appreciate some help with using the jquery parentsUntil method to hide a button until a radio box is selected. I've been struggling with this for a few days now and can't seem to figure out what I'm doing wrong. Any insights would be g ...

Modify a quartet of divs simultaneously

I am currently working on a project that involves 4 input fields, each accompanied by a dropdown element for selecting currency. My goal is to create a JavaScript function that will update all input fields when one of them is changed. For instance, if I s ...

I am currently working on creating a system for displaying rating stars for products. The rating value, which ranges from 0 to 5, has already been provided

class PostBodyRatingStars extends React.Component { render() { const { classes } = this.props var rating = this.props.rating function createMappingArray(rating) { var arr = [] for (i = 0; i < 5; i++) { if (rating >= ...

Creating a dynamic directive in AngularJS: Learn how to add or remove it from the DOM based on specific conditions

Suppose I have a customized modal directive that looks like this: return { restrict: 'E', templateUrl: 'modal.html', scope: { modalContent: "&", modalOpen: "&" } } And in the HTML: <ng-modal modal-content="co ...

Drawing a line beneath the mouse's center using JavaScript

Struggling with my JavaScript drawing tool, particularly the draw() function. The line is consistently off-center below the mouse cursor. How do I fix this issue? My aim is to have the line always follow the center of the mouse as it moves. Could someone c ...

Executing database queries in a synchronous manner in JavaScript

let positionConfig = require('setting'); function retrieveConfig(element) { let setting; positionConfig.find({element: element}, function (err,docs) { console.log(docs[0].current); // show the value setting = docs[0].curr ...

View is unable to trigger the success attribute

Currently, I am delving deep into Backbone JS and facing an issue where the 'success' function in 'EditUser' is not being triggered. I would greatly appreciate it if someone could guide me on what changes I need to make in the code? B ...

Setting response query correctly in Solr using AJAX

Inspired by an example of using Solr's JSON output for AJAX, I have incorporated a drop-down menu into my project form and introduced faceting to the parameters. Parameters: function getstandardargs() { var params = [ 'wt=json' ...

Introduction to Angular initial rendering

I have a straightforward question, but unfortunately I am unsure how to search for it. As my initial page loads, I want Angular to automatically display the first content in <div ng-view>. Subsequently, using $routeProvider takes care of reloading t ...

Leverage JSON data using props in React JS

Currently, my data is formatted in JSON and successfully populated into props known as foxFooterData. Upon inspecting the console.log result of foxFooterData.data, the following information is visible: I am attempting to retrieve the foxFooterCopyright t ...

Tips for displaying an element from an ng-repeat with ng-click action outside of the loop

Looking for help with working on a simple array of objects containing {name,age}? Check out my jsfiddle. I'm currently using ng-repeat to display all the names and am trying to figure out how to display the age of the name when clicked outside of the ...

3 Methods for Implementing a Floating Header, Main Content, and Sidebar with Responsive Design

I am following a mobile-first approach with 3 containers that need to be displayed in 3 different layouts as shown in the image below: https://i.sstatic.net/UjKNH.png The closest CSS implementation I have achieved so far is this: HTML: <header>.. ...

Is it possible to create a website with a single session for all users using JavaScript

Greetings everyone, I am excited to be posting for the first time on stackoverflow. After dedicating a week to learning javascript and achieving some things I am proud of, I have hit a roadblock. As a self-learner, I kindly ask for your understanding. Cur ...

What is the best way to set up Flow type checking for functions passed as props in a React and Redux application?

In my app, I've been passing Redux action creators as props and want to improve type checking. Using the generic Function type has limitations, so I tried using the existential operator (*) in my Props type with no success in getting Flow to infer the ...

Is there a way to display the input value from an on-screen keyboard in an Angular application?

I have included my code and output snippet below. Is there a better way to display the input value when clicking on the virtual keyboard? ...

Unable to detect hover (etc) events after generating div elements with innerHTML method

After using the code below to generate some divs document.getElementById('container').innerHTML += '<div class="colorBox" id="box'+i+'"></div>'; I am encountering an issue with capturing hover events: $(".colorB ...

Issue: There is no specified method of transportation established

I'm facing an issue while trying to create an Outlook calendar event from my application using Express.js. The error message I am receiving is [Error:No transport method defined], and eventually, the response returns as 200 success after approximately ...

Discovering the identical element within the ajax response

The following section is being targeted: var obj = $(this).parent().find('a'); // $(this) is a <UL> inside a <DIV>, but there can be multiple DIV>ULs on the page After that, I retrieve some HTML using $.ajax(). This HTML corres ...

Retrieve the node-postgres result and store it in a separate object beyond the callback function

Currently, I am in the process of converting a data profiling script originally written in Python to JavaScript while following the Wes Bos beginner Javascript Course. This script is designed to take database connection details and a specified target tabl ...

What is the best way to refresh my view model while using chained promises?

I've recently started learning about promises and I'm facing a challenge with updating an object in my view from two chained promises: function Test($resource, FC, UserDetailsService) { 'ngInject'; var self = this; se ...