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

A JavaScript function that is only triggered half of the time

After browsing through various forums like StackOverflow, I couldn't find a solution that perfectly fits my issue. I may be new to programming, but I've managed to create several projects already. Currently, I am working on integrating them into ...

Nuxt.js ERROR: Unable to find reference to 'window' object

Currently working with Nuxt.js and encountering an issue while configuring vuex-persist. Seeking assistance from someone familiar with this problem. store/index.js store/LangModule.js ...

What is the best way to send data from a header component to a separate container component?

Utilizing React-router-dom, I am able to seamlessly switch between components in the following setup: <Router> <div> <Header /> <NavigationBar /> <Switch> <Route exact path ...

Deep-diff JavaScript functions are not permissible for use

In my AngularJS application, I am currently attempting to utilize a JavaScript package. To reference it in my index.html file, I added the following code: <script src="deep-diff-0.3.1.min.js"></script> Furthermore, in my controller, I am usin ...

What is the best method to assign the value of a useState variable to a specific field in an array of objects for inserting data in

**I have a billing form that includes product details for the admin to fill out. One field, labeled "BillID", should automatically populate with a default value of 'Bill ID + 1' through a variable. **Below is the code: const [BillIdFetch, setB ...

IntelliJ has removed the connect-flash plugin, preventing me from reinstalling it

Learning node.js is new to me and I encountered a strange issue. While working on implementing login functionality with passportjs, I faced an error where req.flash() was not functioning properly. Oddly enough, it was working fine yesterday when I used it ...

Alter the hyperlink to a different value based on a specific condition

I need help with implementing a login feature on my app. The idea is that when the user clicks the login button, it should trigger a fetch request to log in with their credentials. If the login is successful, the button's value should change to redire ...

Will terminating a Google Cloud Storage stream impact network usage?

As part of my project, I am developing a media server that will serve streamable audio files. To reduce the number of requests to Google Cloud Storage, I have implemented a caching system. However, one issue I've encountered is that Chrome sends two ...

Tips for stopping links in iOS web applications from launching in a new Safari tab

I am in the process of developing an HTML application specifically for iPads. To enhance user experience, I have added the web app to the homescreen using the "favorite" option. However, I encountered an issue where every internal URL opens in a new Safari ...

The API results are able to be displayed in the console, but unfortunately cannot be shown on the user interface. Any efforts to map the results will result in an Un

Can anyone help me troubleshoot an issue with displaying information from a free API on my page? I'm developing a cryptocurrency app using React, and while I can see the array data with console.log(response.data), I encounter an error when I try to se ...

`Why won't Puppeteer let me pass a variable into a page URL parameter?`

Encountered an error message: Error: Protocol error (Page.navigate): Invalid parameters Failed to deserialize params.url - BINDINGS: mandatory field missing at position 49... The issue arises when trying to pass a variable into the page URL parameter as s ...

Ways to clear the Yeoman index.html cache

Every time I update my Angular app, the old version continues to show up, requiring a "hard" refresh on the browser as a workaround (which is not ideal). My project uses Yeoman (generator-angular) and after examining the Gruntfile.js, I noticed that it re ...

Tips for making a hide and reveal FAQ section

Currently working on creating a FAQ page for my website, I ran into a challenge. My goal is to have a setup where clicking on a question will reveal the answer while hiding any previously open answers. So far, I have managed to achieve this functionality p ...

Is a Javascript-only application compatible with Amazon S3 cloud storage?

I am currently investigating the validity of the following statement: Based on my research, it seems unlikely to create a web application using only JavaScript - without any server-side logic - hosted on Amazon S3 that can also store data solely on S3 whi ...

Is it possible to create a DOM element with a click handler all in one step?

I am looking to dynamically create an element, like this: var productItemTop = $( "<span>" + "<a class='spamItemsX' href='#' " + "onclick=" + eval(launchGenericProductSearch(topProducts)) ...

Automatic playback of the next video in a video slider

Looking to upgrade my video slider functionality - switching between videos, playing automatically when one finishes. Struggling to find a solution that combines manual control with automatic playback. My attempt: function videoUrl(hmmmmmm){ ...

Comment sections that refresh automatically after being posted

I am determined to provide a clear explanation. Despite having some code, I am uncertain about how to make it clone comments and add new ones with user inputted text. Below is the snippet of code I am struggling with: <!DOCTYPE html> <!-- this i ...

Is there a way to have text appear in a popup when I reach it while scrolling?

Is there a way to make the textblocks on my website increase in size or pop up when I scroll down to them? I've attempted to search for a solution online but have been unsuccessful in finding one. ...

Trouble with Angular: Passing output between child components is not working

Just dipping my toes into Angular, I started learning it yesterday for a take-home job interview project. Please excuse any rookie mistakes in advance. For some hands-on practice, I decided to work on a basic project where the main component (app) has two ...

Utilizing Object Arrays in Chart.js for Optimal Performance

I'm struggling with using chart.js to create charts for my admin panel. I'm having trouble figuring out how to properly utilize my JSON array of objects in order to generate the correct dataset. What exactly should I be putting in the data field ...