Combining httpProvider responseInterceptor with $http error callback does not function properly

In my application, I implemented a "loading screen" feature inspired by this post: 'Click'

However, I am facing an issue where all $http requests are triggering the "success" callback, even for URLs that do not exist.

$http.post("this doesnt even exist", { })
.success(function (data, status, headers, config) {
    alert("success"); //even called for non-existing URL
})
.error(function (data, status, headers, config) {
    alert("error"); //never triggered
});

Disabling the 'responseInterceptor' resolves the issue. Everything works as expected, with errors being handled correctly (e.g., exceptions, not found URLs, incorrect parameters).

I am fetching data from a .NET Webservice.

The values of parameters in success callback:

data: ''
status: 0
headers: 'function(name) { ... }'
config: JSON.stringify(config)  '{"method":"POST","url":"this doesnt even exist","data":{}}'

Answer №1

The reason for this issue is that the response interceptor you are using tends to "swallow" the error instead of handling it properly.

In the provided code snippet:

return promise.then(hide, hide);

The first occurrence of hide represents the success callback, while the second refers to the error callback.

Within the hide function itself, the only instruction present is return r;, indicating that it will always return the response.

In order for your $http.post request to recognize an error, the response interceptor should return the promise as rejected like so: return $q.reject(reason);

A potential solution could involve implementing the following logic or utilizing it as a reference point (please note that I have not been able to conduct any testing):

$httpProvider.responseInterceptors.push(function ($q) {
        return function (promise) {
            numLoadings++;
            loadingScreen.show();

            var hide = function () {
                if (!(--numLoadings)) loadingScreen.hide();
            };

            var success = function (response) {
                hide();
                return response;
            };

            var error = function (reason) {
                hide();
                return $q.reject(reason);
            };

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

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

The console experienced a forced reflow when a tooltip appeared on the slider handle while executing JavaScript

I am currently facing an issue with my web page that includes various elements along with the Ant.design slider. The values of the slider are being controlled through React states. However, I have noticed that when the slider tooltip is enabled, the respon ...

Looking to swap out the final value in a JavaScript array?

My task involves manipulating arrays. I start with an array of numbers called newArr. The length of this array is used to create another array filled with zeros, which I named zeroArr. const newArr = [1,3,5,8,9,3,7,13] const zeroArr = Array.from(Array(newA ...

React's input onChange event does not trigger for the second time. It only works the first time

Recently, I developed a React JS application to import images from external sources and process them. To handle the user's onChange event, I utilized the onChange attribute to execute my handleChange function. However, I encountered an issue where it ...

Error in MEAN stack due to absence of hash prefix

Encountering the following error: Error: [$location:ihshprfx] Invalid url "http://localhost:3000/#", missing hash prefix "#!". http://errors.angularjs.org/1.2.16/$location/ihshprfx?p0=http%3A%2F%2Flocalhost%3A3000%2F%23&p1=%23 occurs after executing ...

Any ideas on how to fix the error that pops up during the installation of the bootstrap package in Node

The npm command is not recognized as a valid cmdlet, function, script file, or operable program. Please double check the spelling of the command and ensure that the path is correct before trying again. This error occurred at line 1. npm i bootstrap + ...

Stop the Router from Displaying the Page momentarily prior to Redirecting

Currently, I have set up a session context for my NextJS application where users accessing pages within the /app/ directory are required to undergo an authorization check before being granted access. Although the logic is functioning correctly in redirect ...

Renovating code with the .catch(handleError) function leads to an UnhandledPromiseRejectionWarning

I need to refactor my catch block to use a common approach for multiple requests, but I am encountering an UnhandledPromiseRejectionWarning: ReferenceError: next is not defined. Below is a snippet of the code. user.save() .then(user => { }) ...

The chosen choice is not able to be shown within the option tag

When attempting to filter options using JavaScript based on a selected item, I'm encountering issues. If the selected element contains 'CONTINUE' or 'BRACKET', it should be split into an array by space and only the first two indice ...

Incorporating ngRoute for routing with an Express backend

After reading multiple answers regarding this topic, I am still struggling to grasp the concept. Currently, I have an angular front-end and I am attempting to utilize $routeProvider to load partials for my single page application. However, I keep encounter ...

Mocking a Promise-returning dependency for a React Component in Jest

There's a React component I'm working on that has a dependency like so: import { fetchUsers } from '../../api/'; This function is a utility that returns a Promise. My challenge lies in trying to mock this dependency using Jest. I&apo ...

Discover the process of connecting a REST controller with AngularJS and Spring

I have a list of file paths stored in an array within the scope variable of an AngularJS Controller. My goal is to properly map these file paths to a Java REST controller for further processing. When I pass it as "/ABC/Scope-Variable," it successfully ma ...

When using res.redirect in Express, it not only redirects to a new URL but also allows you to access the HTML

I'm having an issue with redirecting a user to a login page when they click a button. Instead of being redirected, I am receiving the html source code and nothing is happening. My express redirect method is as follows: function customRedirect(req, ...

React TypeScript - creating a component with a defined interface and extra properties

I'm completely new to Typescript and I am having trouble with rendering a component and passing in an onClick function. How can I properly pass in an onClick function to the CarItem? It seems like it's treating onMenuClick as a property of ICar, ...

Tips for sending the setState function to a different function and utilizing it to identify values in a material-ui select and manage the "value is undefined" issue

I am currently utilizing a Material UI select component that is populated with data from an array containing values and options. Within this array, there exists a nested object property named "setFilter". The setFilter property holds the value of setState ...

Arranging arrangements in javascript

I am dealing with objects that contain the fields id and position. const items = [{id: 11, position: 1}, {id: 12, position: 2}, {id: 13, position: 3}, {id: 14, position: 4}, {id: 15, position: 5}, {id: 16, position: 6}]; These objects represent folders st ...

Tips for arranging the items within the slider according to the specified direction (rtl, ltr) in the Owl Carousel slider for Angular

Is there a way to dynamically change the direction of the owl-carousel-o angular slider based on the selected language? Currently, I have set rtl: true in the owl-carousel configuration during initialization. However, when the user switches to a different ...

JavaScript Loading Screen - Issues with window.onload functionality

I am currently working on creating a loading screen for my project. I need to use JavaScript to remove the CSS property "Display: none" from the page, but for some reason, my code is not functioning as expected. The Issue: I discovered that using window. ...

A guide on incorporating dynamic formControlName functionality into AngularJs2

Currently, I am building forms using the form builder in AngularJS2. My goal is to incorporate the formControlName property/attribute into the form element as shown below: <input type="text" formControlName={{'client_name' + i}} placeholder=" ...

Iterate through the loop to add data to the table

Looking for a way to append table data stored in local storage, I attempted to use a loop to add cells while changing the numbers based on row counts. Here is my JavaScript code snippet: $(function() { $("#loadTask").change(function() { var ta ...

Before being sent, CDATA is eliminated

Currently, I am integrating a SOAP call within an Angular application. One requirement I have is to include CDATA for a specific section of the payload for certain calls. angular.forEach(contactsCollection, function (item, index) { contacts = contact ...