"Unleashing the Power of AngularJS: Implementing a Global Error Handler to Display and

When building my website, I have multiple Angular apps that require a global error handler to track and display alerts for errors with codes like 500 and 401. Here is what I have so far:

In order to create a global error handler module, I've set up the following code to inject into my apps:

angular.module('globalErrorHandlerModule', [])
    .factory('myHttpInterceptor', ['$rootScope', '$q', function ($rootScope, $q) {
        return {
            'responseError': function (rejection) {
                if(rejection.status == 500){
                    // show error
                }

                return $q.reject(rejection);
            }
        };
    }])
    .config(function ($httpProvider) {
        $httpProvider.interceptors.push('myHttpInterceptor');
    });

angular.module('myApp', ['globalErrorHandlerModule'])

The challenge I am facing now is figuring out how to actually display the error in an alert. I attempted creating a separate error app and sharing a data factory between them, but the data isn't updating within the app. This is what I tried:

angular.module('globalErrorHandlerModule', [])
    .factory('myHttpInterceptor', ['$rootScope', '$q', 'Data', function ($rootScope, $q, Data) {
        return {
            'responseError': function (rejection) {
                if(rejection.status == 500){
                    // set error
                    Data.error.message = '500 error';
                }

                return $q.reject(rejection);
            }
        };
    }])
    .factory('Data', function () {
        var _error = {
            message: "init"
        };
        return {
            error: _error
        };
    })
    .config(function ($httpProvider) {
        $httpProvider.interceptors.push('myHttpInterceptor');
    });

angular.module('globalErrorHandlerApp', ['globalErrorHandlerModule'])
    .controller('GlobalErrorCtrl', function ($scope, Data) {
        $scope.test = Data.error.message;
    });

I then attempted to display the error as follows:

<div ng-controller="GlobalErrorCtrl">
         Error {{test}}    
</div>

Unfortunately, I only see the initial value and not any updates to the error message. I also tried broadcasting without success. I believe there must be a more effective way to implement this feature, but I haven't discovered it yet. Any guidance or tips would be greatly appreciated. Thank you.

Answer №1

Give this a shot

angular.module('appErrorHandling', ['errorHandlingModule'])
.controller('ErrorHandlerCtrl', function ($scope, Data) {
    $scope.display = Data.error;
});

It's always better to watch an object instead of a string. Let me know if this helps you

<div ng-controller="ErrorHandlerCtrl">
     Error <span> {{display.message}}   </span>  
</div>

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

Attempting to modify the state within a nested object located in an array by using json data

My objective is to retrieve data from the Google Books API, which returns JSON data in a similar format to what my state displays. I aim to update the title with the title string provided by the JSON data. Currently, I am encountering a "failed to compile" ...

What is the best way to transform a string representation of data into an array and then showcase it in

After importing CSV data and converting it into the variable stringData, I am facing an issue when trying to display this data in a React table. Although I have attempted to use the map function to separate the headers and map to <th>, displaying t ...

JavaScript on Ruby on Rails stops functioning in js.erb file

I have encountered an issue with pagination using AJAX in a view. Initially, I had two paginations working perfectly fine with their respective AJAX calls. However, when I tried to add a third pagination (following the same method as the previous two), it ...

Transform a text node into an HTML element with the help of JQuery

Consider this HTML snippet: <div> Lorem ipsum <span>dolor sit</span> amet <span>consectetur adipiscing elit</span> eiusmod tempor </div> To select the text nodes [Lorem ipsum, amet, eiusmod tempor], ...

What is the process for sending a request to a static resource along with parameters?

I currently have a node.js restify server running, along with a folder containing static resources. const restify = require('restify') let server = restify.createServer() server.listen(8080, function () { console.log('%s listening at ...

Sharing NPM Scripts Via a Package to be Utilized by Project upon Installation

I have streamlined my linting setup by consolidating all configuration and related packages/plugins/presets (for prettier, stylelint, eslint, commitlint) into an npm package. This allows me to utilize the same setup across multiple projects, simply extendi ...

Tips for displaying XML content within an AngularJS application using HTML

I have a string containing data: var xml = "<rss version='2.0'><channel><title>RSS Title</title></channel> </rss>" ; My goal is to display this string on a web page in the proper XML format. <channel& ...

Guide to storing user data retrieved from the LinkedIn API into an Angularjs controller with the help of a personalized service

Hey there, I'm currently diving into Angular and facing a challenge with saving user information from LinkedIn API to the controller's scope without directly passing it to my custom service. It seems like that might not align with the best practi ...

JQuery Slider's Hidden Feature: Functioning Perfectly Despite Being Invisible

Having an issue with a jQuery slider on my local HTML page. The sliders are not showing up as intended. I want it to display like this example: http://jsfiddle.net/RwfFH/143/ HTML <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery ...

Tips for updating the icon based on the active or inactive status in ag-grid within an angular application

HTML* <ng-template #actionButtons let-data="data"> <div class="cell-actions"> <a href="javascript:;" (click)="assign()"> <i nz-icon nzType="user-add" nzTheme= ...

Tips for implementing ngChange within a personalized directive

Looking to create a directive for a toggle button, here is the code I want to include in the directive: <div class="toggle-button" ng-class="{true: toggleTrue === true, false: toggleTrue === false}"> <button class="true" ng-click="toggleTrue ...

Attempting to input data into elements that have been generated automatically

Trying to set values to elements with automatically generated id's: This code is functional: <input type="tekst" id="<?php echo $item->getId();?>"> <script> document.getElementById("<?php echo $item->getId();?>").v ...

Having trouble getting my angular form validation to function properly

Even though I disabled Bootstrap's validation while using Angular, the validation for every input field still doesn't work. It seems like I have everything set up correctly. My code looks like this below with no success on input validation: < ...

Utilize React to dynamically load diverse data arrays into a slick slider component

I am currently working on a component that includes a slider displaying photos linked to different rooms. The next step is to move this slider to a separate page or component, which will display content for rooms, news, and promotions using different arr ...

Discovering the file extension and ensuring its validity when imported from Google Drive

I am facing an issue with a select tag that has 3 options: powerpoint, pdf, and spreadsheet. When uploading from Google Drive, there is no validation in place, so I can give a ppt link to the pdf option and it will still upload. Can someone help me with va ...

Transferring information to modal without using AngularUI

I'm currently working on an Angular application and facing an issue with passing data from my controller to a modal. Here is the HTML code on my index page: <!DOCTYPE html> <html lang="en" ng-app="myApp"> <head> ... </head> & ...

Tips for accurately determining the count, rather than the character length, of JSON data

After running my code, I believe it returns a JSON array. The resulting JSON array is then stored in a JavaScript variable called 'result'. When I console.log(result); in Firefox, the output shown is: [{"id":"G24","value":"Zas, S"},{"id":"G75" ...

Leveraging Vue.js plugin within a single file component

I am looking to utilize the vue-chartkick plugin in my Vue application, but I want to register it within my single-file components instead of globally. Is there a way to achieve this same functionality without using Vue.use(VueChartkick, { Chartkick })? ...

Is it possible to utilize a slot within a Vue.js loop?

I am encountering an issue with a template that is utilizing v-for to loop through. The template includes a named slot where the name is dynamically assigned within the loop. However, no content is displaying as expected. Can someone help me identify wha ...

What is the best way to deactivate certain JavaScript functions on my webpage when accessed through a mobile device?

Is there a way to disable specific JavaScript functions when accessing my website from a mobile device? While I can achieve this using CSS only, certain buttons require JavaScript functionality. Below is the internal JavaScript code: var menuBtn = docume ...