Different approach to handling response interceptors in AngularJS framework

Is there an alternative to $httpProvider.responseInterceptors since it has been discontinued in AngularJS V1.3?

The interceptors that were functioning with Angular JS 1.2 are no longer operational in version 1.3

var angularErrorHandling = angular.module('xx-http-error-handling', []);
angularErrorHandling.config(function ($provide, $httpProvider, $compileProvider) {
    var elementsList = $();

     // add a function to intercept the http responses of the entire application
    $httpProvider.interceptors.push(function ($timeout, $q) {
        return function (promise) {
            return promise.then(function (successResponse) {                
                // handle successful responses for GET requests
                if (successResponse.config.method.toUpperCase() == 'GET') {
                    var length = successResponse.data.length;                    
                    if (length == 0)
                    {
                        var countactivetoaster = $('#toast-container').find('.toast').length;
                        if (countactivetoaster == 0) {
                            toastr.warning('No Records Found!', '');
                        }
                    }                    
                    return successResponse;
                }
                else if (successResponse.config.method.toUpperCase() == 'PUT') {                   
                    toastr.success('Data Saved Sucessfully..', '');
                    return successResponse;
                }
                else if (successResponse.config.method.toUpperCase() == 'POST') {                   
                    toastr.success('Data Saved Sucessfully..', '');
                    return successResponse;
                }
            },
            // handle unsuccessful responses and display error messages
            function (errorResponse) {
                switch (errorResponse.status) {
                    case 400: // Display error for status code 400                           
                        toastr.error('400 error.', '');
                        // Display validation error messages if present
                        if (errorResponse.data.errors.length > 0) {
                            for (var i = 0; i < errorResponse.data.errors.length; i++) {
                                toastr.error('xx-http-error-validation-message', '');
                            }
                        }
                        break;
                    case 401: // Error message for status code 401                            
                        toastr.error('Wrong email address or password!', '');

                        break;
                    case 403: // Inform user about authorization denial                          
                        toastr.error('You have insufficient privileges to do what you want to do!', '');
                        break;
                    case 500: // Internal server error message for status code 500                            
                        toastr.error('Error: <br />' +
                            errorResponse.data.exceptionMessage != null && errorResponse.data.exceptionMessage.length > 0 ? errorResponse.data.exceptionMessage : 
                            errorResponse.data.message, '');
                        break;
                    default: // Default error message for other errors                            
                        toastr.error('Error ' + errorResponse.status + ': ' + errorResponse.data.message, '');
                }
                return $q.reject(errorResponse);
            });
        };
    });

    $compileProvider.directive('httpErrorMessages', function () {
        return {
            link: function (scope, element, attrs) {
                elementsList.push($(element));
            }
        };
    });
});

Answer №1

It is recommended to utilize the new interceptor syntax, which offers a cleaner and more efficient approach:

With this new syntax, you have the ability to manage 4 interceptors separately: request, requestError, response, and responseError.

// To implement the interceptor as a service
  $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
    return {
      // optional method
      'request': function(config) {
        // handle successful requests
        return config;
      },

      // optional method
     'requestError': function(rejection) {
        // handle errors during request
        if (canRecover(rejection)) {
          return responseOrNewPromise
        }
        return $q.reject(rejection);
      },



      // optional method
      'response': function(response) {
        // handle successful responses
        return response;
      },

      // optional method
     'responseError': function(rejection) {
        // handle errors in response
        if (canRecover(rejection)) {
          return responseOrNewPromise
        }
        return $q.reject(rejection);
      }
    };
  });

  $httpProvider.interceptors.push('myHttpInterceptor');

For more details, refer to: https://docs.angularjs.org/api/ng/service/$http (Interceptor chapter)

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

Get the selected value from a dropdown list in Angular after populating the options

I am working with a model within an Angular module. $scope.employee = {} $scope.countries={} $scope..employee.Country_id = 10 $scope.employee.City_id = 50 Next, I am binding two select elements in the following way: $http.get("/api/initdataapi/GetCountr ...

Tips for managing Express.js callbacks and modifying an object's property from within a function

I am currently working with two JavaScript files. I have successfully retrieved data from MongoDB using the method bookDao.getActiveBookByCategoryId(). The Issue I Am Facing: Within the categoryDao.js file, I am attempting to update the resultJson.book_c ...

JSON.Parse allows for graceful degradation of data when handling JSON objects in JavaScript

What should be done if a browser does not support JSON.parse? Would it be appropriate to include json.js and use parseJSON instead? Here's an example of how the code could look: var output; if (JSON.parse) output = JSON.parse(data); else ou ...

Merge various JavaScript files together into a single consolidated JS file

I've been working on my web application with jQuery and am looking to incorporate multiple additional jQuery script files into one page. After doing some research, I found that Google recommends consolidating all of the jQuery script files into a sin ...

Create a system where three arrays are interconnected, with the first array representing the name of the object

I have a group of different objects structured like this: let object1 = { xyz: 'xyz1', arr: [] }, object2 = { xyz: 'xyz2', arr: [] }, object3 = { xyz: 'xyz3', arr: [] } Manag ...

Dividing an Image into segments using Javascript

I'm currently working on a basic Jigsaw puzzle project. To achieve this, I am required to divide the image I've selected into 20 separate pieces. I was wondering if there is a method in Javascript that can automatically cut an image into 20 equal ...

Preventing Cross-Site Scripting (XSS) vulnerabilities during the

When my site stores user-generated HTML to be rendered on a web page, what are the best practices to avoid XSS attacks? Is simply stripping <script> and <iframe> tags sufficient protection? Will this safeguard work across all browsers? I have h ...

How can I place a THREE.ArrowHelper on a specific layer in Three.js?

Exploring the world of Three.js, I'm striving to understand how to organize elements onto separate layers. One of the challenges I'm facing involves an ArrowHelper that I've set up and added to the scene in the following manner: var ar ...

When using fs.readFileSync, the error message "no such file or directory" may appear even though the file is successfully returned when using require()

Looking to dynamically read a JSON file poses a challenge with the traditional require() method. The issue lies in the fact that the file is not updated until the NodeJS server is restarted, prompting the need to utilize fs.readFile or fs.readFileSync. Wh ...

There is no result being returned by Model.findOne()

Why does Model.findOne() return null even when a valid collection is present in the respective Model? app.post("/fleetManagement", (req, res) => { const requestedDriverID = req.body.driverId; console.log(requestedDriver ...

Can the Vue instance be accessed in Axios interceptors?

I've integrated vue-reactive-storage to have a reactive alternative to localStorage in my Vue application. This plugin creates a vue object that is accessible to all components. I'm facing an issue when trying to access this object within my axio ...

Adapting npm scripts with Node.js based on the current context

Can you set up package.json to execute a different npm start script depending on the context? For instance, I want to run DEBUG=http nodemon app.js during development. However, I prefer to run node app.js in production. ...

Running the Jcrop function multiple times within another function will not result in execution

When I click on the 'Edit A' link, a window opens where I can use Jcrop for editing. The process works smoothly for the first image. However, when I try to edit the second image using the 'Edit B' link, it keeps displaying the first ima ...

Add data to a nested array with Vuex

Currently, I am facing a challenge with adding an object to a nested array in Vue using store / vuex. While I have successfully updated the main comments array with a mutation, I am struggling to identify the specific main comment to which the new reply ob ...

Three.js: Buffer geometry does not provide any performance improvement

After examining the Three.js example found at webgl_performance, I decided to try improving performance by converting the model into a buffer geometry using the following code: var buffer = THREE.BufferGeometryUtils.fromGeometry( geometry ); Despite my e ...

When making a $http request in Angular, the passport req.isAuthenticated method consistently returns false

I have implemented user authentication in my application using passportjs. When testing with postman, the login process is successful and req.isAuthenticated always returns true in subsequent requests after logging in. However, when using angular $http f ...

The 'id' property cannot be accessed because the data has not been retrieved successfully

After loading my App, the data from Firebase is fetched in componentDidMount. I am currently passing postComments={comments} as a prop. However, before this happens, my app crashes with Cannot read property 'id' of undefined on line const c ...

The method continues to receive null values from Ajax despite successfully retrieving the data from Facebook

My current challenge involves creating a login using Facebook. The console indicates that the requested data (email, first_name, etc.) is being retrieved successfully, but for some reason, the AJAX request keeps sending null data to the PHP method. Below ...

Setting the 'redirect_uri' for Identity Server 4 in a React JS application and directing it to a specific view using a route

After following the instructions at , I attempted to login to Identity Server from my ReactJS application. Upon successful login, http://localhost:3000/callback.html was loaded with id_token and access_token in the URL. However, I noticed that this callbac ...

In JavaScript, a button is programmed with a rare 1.04% probability of directing to Page A and a much higher 98.96% likelihood of redirecting to Page

My goal is to create a button that, when clicked, will have a 1.04% probability of navigating to Page A and a 98.96% chance of going to Page B. The challenge I'm facing is in randomizing these results using JavaScript. I am fairly new to this language ...