"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

NextJS - The server attempted to execute the find() function, which is only available on the client side

When attempting to utilize the .find method within the server component, I encounter an error. export async function TransactionList() { const transactions = await fetch('/transactions'); return ( <ul> {transactions.m ...

Is there a way to inform the List component when the height of its row items has been altered in order to trigger a rerender

In my project, I am using a react-virtualized List where each item in the rows has an expand button. When this button is clicked, the row's height changes to reveal more information. The problem I am facing is that after clicking the button, the inne ...

Dealing with AngularJS ng-model problems when duplicating a form

Currently, I am facing an issue with sending parameters to control and require some guidance. I have multiple types of questions within the ng-repeat loop named 'question' that I am iterating through. The problem arises when there are two questi ...

What is the best way to import a file in meteor version 1.3?

Trying to incorporate react-datepicker into a meteor 1.3 and react project has been quite successful so far. The only issue I am facing is the inability to access any of the css styles from the package. According to the readme, I'm supposed to requir ...

Merging values of different keys in a .json file

Check out my json file below: { "foo": "https://3a1821d0.ngrok.io/api/foo", "bar": "https://3a1821d0.ngrok.io/api/bar", } I am interested in changing the key 3a1821d0 to a different variable within the json structure, like so: { "some_variab ...

Is there a way to assign a value to an Angular-specific variable using PHP?

In the development of my Angular 4 application, I encountered an issue while receiving JSON data based on an id value through a PHP script. Upon examining the code, it seems that there should be a value passed into this.PropertiesList. examineProperties(i ...

What is the best way to create a reset button for a timing device?

Is there a way to reset the timer when a button is clicked? Having a reset button would allow users to revisit the timer multiple times without it displaying the combined time from previous uses. Check out this code snippet for one of the timers along wit ...

The Handlebars helper needs to provide a result when a value is present

I have created a Handlebars helper function like this: Here is the code in my JavaScript file: Handlebars.registerHelper('switch', function (sw_val, options) { if (sw_val != '*NONE' && sw_val != false && sw_val != ...

How do I programmatically switch the Material-UI/DatePicker to year view in React?

I have a DatePicker component set up in my project, and it works perfectly fine. However, for my specific use case, I only need the year view to be displayed. Within the child component of the DatePicker (Calendar), there is a function called: yearSelect ...

Using JQuery to switch classes and activate events

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <body> <span class="fake_h">Too</span> </body> <script> $('.fake_h').click(function() { $(this).addClass( ...

Updating controller variables when the route changes in AngularJS

I'm new to the AngularJS scene and I've encountered a challenge. My goal is to have the selected tab change dynamically based on the URL changes. Here's my JavaScript code: app.config(function($routeProvider, $locationProvider){ $rou ...

Creating pagination using AJAX to fetch data from an API while maintaining the same query parameters

Writing a title for this may be a bit tricky, but I'll try my best. On the webpage located at the /music-maker endpoint, there is a modal that contains an input field. This input field captures user input and sends it to the backend using AJAX. The u ...

Creating or updating JSON files using Node.js

I am currently working with JSON files that contain an array of objects. I am looking to update one of these objects and subsequently update the JSON file by overwriting the old file. I understand that this cannot be achieved using AngularJS, but rather wi ...

What is the method for retrieving a property from an object contained within an array that is assigned to a property of another object?

How can I retrieve the name property from the subjects array within a course object? The database in use is mongodb. Modifying the course model is not an option. The course model : const mongoose = require('mongoose'); const Schema = mongoose. ...

Determine the output based on the data received from the ajax post request

I am seeking a way to validate my form based on the data returned. Currently, the validation only returns false if the entire post function is false. Is there a solution to differentiate how it is returned depending on which condition is met? This is my ...

Tips on inserting javascript to modify the CSS class of a table data cell in a Flask WTF jinja2 table based on the cell's value

I have integrated Flask WTF to showcase the results of a database query. I am seeking a way to modify the cell background color to light red if the value is below 25. I am unsure about where and how to embed the JavaScript code to validate the cell value a ...

Adjust the stacking order of bars in a vertical chart and exclude negative values with Vega-Lite

I am utilizing this chart as a guide for my current project Explore Vega Editor here Is there a way to rearrange the order of the 'Measure' while keeping 'Measure 1' at the top, disregarding its negative value? I want to display the & ...

Button missing post ajax loading

I've encountered a problem with my code that populates a table and contains buttons, which trigger an AJAX load. The content is loaded into a DIV with the ID 'DIV1', but when I try to access the buttons in that DIV1 by clicking on them, they ...

Are queued events in React discarded upon a state change?

As I develop a React form component with simple validation, I encounter an issue where the onBlur event of a field and the onSubmit function of the form are triggered simultaneously. If there is a change in the state during onBlur, the onSubmit function do ...

Exploring JSON data for auto-complete suggestions

Upon receiving the object from the source, it looks like this - ["road",[["road",53,"0E"],["roadtrip",53,"1E"],["roadrunner",53,"2E"],["roadster",53,"3E"],["roadside",53,"4E"],["roadrage",53,"5E"],["roadcycling",53,"6E"],["roadsideamerica",53,"7E"]],{"k": ...