Identifying all failed http GET requests

Within my application, there is a grid that retrieves data through HTTP promises. Currently, I am able to recognize errorCallbacks - as demonstrated below:

myDataPromise.then(function () {
    //do stuff
}, function errorCallback(response) {
        if (response.statusText === "Not Found") {
            //do stuff
        }else if(response.statusText === "Internal Server Error"){
            //do stuff
        }

However, in the case of an SSL error, such as "ERR::CONNECTION REFUSED" returned by Chrome, I am unable to detect it as easily as I can with 404 errors, for example. What I really want is to show a simple message or image indicating that there was an error in retrieving the user's data, regardless of the specific error. If an HTTP GET request fails in any way, the user should be informed. This requirement seems common, yet I am having trouble finding relevant information online.

Answer №1

To implement an interceptor, you must follow these steps:

 // create the interceptor as a service
$provide.factory('myHttpInterceptor', function($q, dep1, dep2) {
  return {
    'request': function(config) {
      // do something with the request
      return config;
    },

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

    'response': function(response) {
      // handle response success
      return response;
    },

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

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


// Alternatively, use an anonymous factory to register the interceptor
$httpProvider.interceptors.push(function($q, dep1, dep2) {
  return {
    'request': function(config) {
       // implement request logic here
    },

    'response': function(response) {
       // implement response logic here
    }
  };
});

This interceptor will capture all $http requests, including template loading.

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

Is it possible to hide and reveal specific form elements based on the selection of a checkbox?

Having issues with the code provided below, it's not working as expected. Can you help me figure out what I might be missing? HTML: <input id="id_code_col" type="checkbox" name="code_col"></input> SCRIPT: $(document).ready(function(){ ...

single calendar bootstrap-datepicker allowing users to select date ranges

Is it possible to create a single calendar range date picker with Bootstrap instead of using two separate calendars? Currently, I have implemented a solution with two calendars. $('#datepicker').datepicker({ }); <link href="https://cdnjs.cl ...

Is there a way to selectively add elements to the Promise.all() array based on certain conditions?

Here is the code snippet that I have written: I am aware that using the 'await' keyword inside a for-loop is not recommended. const booksNotBackedUp: number[] = []; for (let i = 0; i < usersBooks.length; i += 1) { const files = await ...

Setting response character encoding in Node.js/Express - how is it done?

Assume I have the following code: app.get('/json', function(req, res) { res.set({ 'content-type': 'application/json' }).send('{"status": "0"}'); }); I've been attempting to send the response as ...

Is it feasible to insert the result of a JavaScript code into a PHP script?

Alternatively, you can view both codes side by side on the panelbackup(dot)com/codes page Alright, I have a code placed on page 1.html that adds four random numbers at the end of any given URL: <head><script>window.onload = function() { ...

Unable to conceal adjacent element when z-index is set as 1

I encountered an issue where a modal is overlapping another element, and the close button of the underlying element has a z-index of 1. Despite creating a new modal with its own close button, the original close button remains visible on top. I attempted t ...

Is Dart the new AngularJS in terms of programming style?

Is there a software library or project available that allows for programming in Dart using an AngularJS style approach? I am interested in creating annotated HTML files to declare my UI rather than instantiating everything imperatively like with SWT. I wo ...

What is the best method for gracefully opening external links in a reusable new tab?

Here is the progress I have made so far: <script> var win; function OpenInNewTab(url ) { // var win; if (win) { win.close(); } win =window.open(url, 'myWin'); win.focus(); } </script> My links are structured like ...

Develop an array of unique objects with multiple dimensions, ensuring no duplicates are included

Seeking assistance for the following task: I am trying to create a new multidimensional array of objects based on an existing array of objects: [ {number:111, connectedNumber: 112, ...}, {number:112, connectedNumber: 111, ...}, {number:113, connectedNumbe ...

What is the best way to extract the class name from ui.item or event using the function(event, ui)?

Is there a way in jQuery to extract the class name from a function with two parameters, event and ui? For example, consider the following code snippet: $(document).tooltip({ show: null, position: { my: "left top", at: "left bottom ...

Is it acceptable to include the bundled main.js file in the gitignore for a HUGO project?

Is it possible to exclude the bundled main.js file from a HUGO project by adding it to .gitignore? ...

Obtain information from YouTube and format it into a list item

Currently, I'm working on compiling a list of videos that includes the title, link, image, and creator of each video. It's been a bit challenging :S <script type="text/javascript"> $(document).ready(function(){ $.getJSON('http://gdata ...

Transforming a massive JSON object into a Blob concerns directly converting it into an ArrayBuffer or Blob to prevent exceeding the maximum string length error

Situation: Within my application, I am encountering the following code: let blob = new Blob([JSON.stringify(json)], {type: "application/json"}); This code sometimes fails because the maximum string length allowed in Chrome is approximately 500M ...

JavaScript code to copy a specified column through the last column, and then paste it down to the last row

I have limited experience with JavaScript and I've been putting together the code I need by searching online resources and watching videos. My goal is to set multiple columns in row 4, starting from column 18 to the last column, as the active cells fo ...

Leveraging JavaScript and PHP for fetching image files and generating a downloadable zip folder

Currently, I am in the process of creating a Safari extension specifically designed for imageboard-style websites. One of the key features that I am eager to incorporate is the ability to download all images that have been posted on the site (not including ...

JavaScript: Selecting parent elements using getElementsByClassName

I am dealing with the following HTML code: <div class="item"> <img class="item-image" src="${item.getImage()}"/> <p>${item.getName()}</p> </div> and JavaScript: var classname = document.getElementsByClassName("item" ...

Component does not render on router.push('/page') without reloading first

After a successful login, I am storing the user token in browser cookies and using router.push('/dashboard') to redirect the user to their dashboard. However, the '/dashboard' page does not display any components until a manual reload i ...

Error Encountered: ModalInstanceProvider Not Found

Just diving into AngularJS and struggling to decipher the meaning behind this error. I noticed others encountering a similar issue, but it doesn't appear to align with my specific problem. Unknown provider: $modalProvider <- $modal error with Angu ...

Tips for accessing payment details from a stripe paymentElement component in a React application

Here is a basic code snippet for setting up recurring payments in Stripe: await stripe ?.confirmSetup({ elements, confirmParams: { return_url: url, }, }) After browsing through the documentation and the internet, I have two unanswere ...

JavaScript Dynamic Array for Generating GoogleChart JSON Data

I am attempting to create a line chart using Google Charts ( ), but I am struggling with formatting the array for the chart. The required array format is as follows : var data = google.visualization.arrayToDataTable([ ['Year', 'Sales&ap ...