Dealing with universal Ajax error handling in AngularJS

Previously on my website when it was 100% jQuery, I employed this method:

$.ajaxSetup({
    global: true,
    error: function(xhr, status, err) {
        if (xhr.status == 401) {
           window.location = "./index.html";
        }
    }
});

to establish a universal handler for handling 401 errors. Presently, I have transitioned to using angularjs along with $resource and $http for my server requests. Is there an equivalent approach in angular to set up a global error handler?

Answer №1

While developing my website using Angular, I encountered the challenge of handling global 401 errors. After reading a helpful blog post, I decided to implement an HTTP interceptor to address this issue. You may also benefit from checking out the blog post titled "Authentication in AngularJS (or similar) based application.", published by espeo software.

EDIT: Here's the final solution I implemented:

angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives'], function ($routeProvider, $locationProvider, $httpProvider) {

    var interceptor = ['$rootScope', '$q', function (scope, $q) {

        function success(response) {
            return response;
        }

        function error(response) {
            var status = response.status;

            if (status == 401) {
                window.location = "./index.html";
                return;
            }
            // otherwise
            return $q.reject(response);

        }

        return function (promise) {
            return promise.then(success, error);
        }

    }];
    $httpProvider.responseInterceptors.push(interceptor);

Answer №2

Kindly take note that responseInterceptors are no longer supported as of Angular 1.1.4. The following snippet is extracted from the official documentation, demonstrating the updated approach for implementing interceptors.

$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  return {
    'response': function(response) {
      // handle success scenario
      return response || $q.when(response);
    },

   'responseError': function(rejection) {
      // handle error scenario
      if (canRecover(rejection)) {
        return responseOrNewPromise;
      }
      return $q.reject(rejection);
    }
  };
});

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

This is the implementation in my project using Coffeescript:

angular.module("globalErrors", ['appStateModule']).factory "myHttpInterceptor", ($q, $log, growl) ->
  response: (response) ->
    $log.debug "success with status #{response.status}"
    response || $q.when response

  responseError: (rejection) ->
    $log.debug "error with status #{rejection.status} and data: #{rejection.data['message']}"
    switch rejection.status
      when 403
        growl.addErrorMessage "You don't have the right to do this"
      when 0
        growl.addErrorMessage "No connection, internet is down?"
      else
        growl.addErrorMessage "#{rejection.data['message']}"

    // handle error scenario
    $q.reject rejection

.config ($provide, $httpProvider) ->
  $httpProvider.interceptors.push('myHttpInterceptor')

Answer №3

To implement the HTTP interceptor, follow these steps:

(function(){
  var httpInterceptorSetup = function ($provide, $httpProvider) {
    $provide.factory('httpInterceptor', function ($q) {
      return {
        response: function (response) {
          return response || $q.when(response);
        },
        responseError: function (rejection) {
          if(rejection.status === 401) {
            // Unauthorized access
          }
          return $q.reject(rejection);
        }
      };
    });
    $httpProvider.interceptors.push('httpInterceptor');
  };
  angular.module("appModule").config(httpInterceptorSetup);
}());

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

`Angular project not responding to HTML mouse click event`

I am a beginner with the Angular framework and currently experimenting with creating a basic button in the app.components.html file. My goal is to have this button trigger a function declared in the app.component.ts file. Initially, I used the (click) even ...

Guide on how to use Vue's watch feature to monitor a particular property within an array

I am interested in observing the "clientFilter" within an array TableProduit: [ { nr_commande: 0, date_creation: "", id_delegue: "1", clientFilter: "" } ], ...

Ways to dynamically update a MYSQL field in PHP without the need to refresh the page

Is there a way to update MYSQL data using text input instead of a submit button? I want the admin to select an option from a dropdown menu and then click 'save' to update the MYSQL records. Can this be done using AJAX or jquery? This is what I h ...

Issues persist with redirection when using AJAX and PHP in a login form, resulting in the user staying on the index page

After filling out both the email and password form fields and clicking the sign-in button, my script is functioning correctly. However, upon clicking the sign-in button, I want the user to be redirected to the home page. Currently, the user remains on the ...

A ServiceWorker used a promise in FetchEvent.respondWith() that resulted in a non-Response value of 'undefined'. This caused an issue in browser-sync

There are times when my server encounters an error in the console: Failed to load ‘http://localhost:3000/browser-sync/socket.io/?EIO=3&transport=polling&t=Lm2wn4p’. A ServiceWorker passed a promise to FetchEvent.respondWith() that reso ...

Strictly allowing numerical values to be entered into an input field using Angular, without relying on HTML5 features

Is there a way in Angular to restrict a field so that it only accepts numbers? I am familiar with using input type="number" for this purpose traditionally, but curious about how it can be done best in Angular. ...

"Can someone provide guidance on extracting the ID from a JSON value and storing it in a

Hey there, I have come across this jQuery code snippet: var fbuid = zuck; var fbjson = $.getJSON("https://graph.facebook.com/"+fbuid); I am wondering how to extract the id directly from the JSON response into a variable : { id: "4", first_name: "Mark", ...

Sending DOM values to React components as properties

Forgive me if this question seems basic, as I am still learning ReactJs. I have a react component that displays the user's sign-in status: <AccountStatus iconsize="medium" activate={[true,false,true]}/> Image 1 //or using <AccountStatus i ...

Rearrange the order of items in the fancybox gallery

Typically, fancybox displays items in the gallery based on the order they are added in the HTML code. Is there a way to customize the order of items when they are opened in the popup, while keeping the original order when displayed on the page? The solut ...

Avoid showing a pop-up window when switching to a different page

I have a pop-up window that displays a confirmation message only when I am trying to close the browser/tab. It is working on my page, but it also appears when I navigate to another page. I want the pop-up window to only show up when I try to close the ta ...

Flowing Waterways and Transmission Control Protocol

I have a unique piece of code that I recently discovered. After running it, I can connect to it using a Telnet client. const network = require('networking'); //creating the server const server = network.createServer(function (connection) { ...

Loading asynchronous select options with a knockout observable array

I have an ajax-based asynchronous loader for select options. It accepts a remote address and returns an observable array that is correctly populated with descriptions and key values to be used in the following binding. <select data-bind="value: select ...

How to use jQuery to dynamically set the value of a column span in a

Struggling with setting the value for a table column span. Here is my jQuery code: $('tr td data-th=Name span').val('My span content...'); This is how my HTML appears: <tr> <td data-th="Name"><span class="edit-inpu ...

Retrieving information from Prismic API using React Hooks

I'm having trouble querying data from the Prismic headless CMS API using React Hooks. Even though I know the data is being passed down correctly, the prismic API is returning null when I try to access it with React Hooks. Here is my current component ...

extracting information from intricate JSON structures with the assistance of AngularJS

When it comes to fetching JSON data from a REST API link using AngularJS, I find myself in a bit of a pickle. After making an HTTP GET call in the controller, I struggle to properly display the data in the view. The JSON structure is quite complex, with o ...

Adjust the size of the div to match its parent's size when resizing

Can a div be resized to match its parent's size on window resize? Here is the current HTML code: <div class="sliderContainer"> <div id="cyler"> <div class="cy1" style="background-image:url(images/Keggy_Banner_Ie.jpg); back ...

What is the process for transforming OpenTopography point cloud color data from NSF into RGB values?

I'm currently working on a small project focused on visualizing NSF OpenTopography data in a point cloud using three js. While I've been able to plot the data points successfully, I'm struggling to understand the color values associated with ...

Is the canvas refusing to disappear?

My HTML5 Canvas element is not disappearing as expected. I wrote a timer function to hide the element when the timer hits 0. I tested this using an alert flag and it worked perfectly. Problem: if (TotalSeconds <= 0) { ctx.clearRect(0, 0, canvas.w ...

Using async/await does not execute in the same manner as forEach loop

Here is a code snippet that I have been working with. It is set up to run 'one' and then 'two' in that specific order. The original code listed below is functioning correctly: (async () => { await runit('one').then(res ...

Tips for styling list tooltips with CSS and Bootstrap

I am looking to style my tooltips using CSS, specifically I want the background of the tooltips to be gray and the text to be bold. The issue is that I am unsure how to do this, especially since I have a list with multiple options, each option having its ...