Angular is attempting to call the $http method and trigger the success callback even

I have implemented a function in a service:

function retrieveData(link) {
    return $http.get(link).then(function (res) {
        return res.info;
    });
}

If the request is successful, everything works smoothly - I receive a promise as expected.

However, if I provide a URL that triggers a 404 error, I encounter the following:

TypeError: Cannot read property 'info' of undefined

This error occurs on the line: return res.info;

Upon inspecting the Chrome Developer Tools, I can confirm that the GET request returns a 404 status code.

Why is Angular (v1.4.7, Tried v1.5.0 as well) passing undefined to my successCallback in case of an error?

(My intention is to handle failures in the calling code.)

Edit: @jcaron provided a helpful hint. The problem seems to stem from this configuration line (created by another developer):

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

There appears to be a flaw in the design of the interceptor:

function ErrorInterceptor($q, $window) {
    return {
        response: function (response) {
            return response;
        },
        responseError: function (response) {
            if (response.status === 500) {
                $window.location.href = '/error';
                return $q.reject(response);
            }
        }
    };

Answer №1

There seems to be a flaw in the design of the interceptor

It is evident that there is a problem. Whenever a rejection occurs that is not a 500 status, the interceptor returns undefined, fulfilling the promise. The correct approach would be

…
responseError: function (err) {
    if (err.status === 500) {
        $window.location.href = '/error';
    }
    return $q.reject(err); // ensure rejection is transmitted
}

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

I encountered issues with my Bower calls being blocked by the corporate proxy, which resulted in errors when attempting to update my

When attempting to install bower through npm for the angular seed project setup, I encountered errors due to my corporate proxy causing issues. retry Request to https://bower.herokuapp.com/packages/angular failed with ECONNRESET, retrying in 1.2s bower ...

MUI-Datatable: Is there a way to show the total sum of all the values in a column at once

I have a column displaying the Total Amount, and I am looking for a way to show this totalAmount. After conducting some research, it seems like onTableChange is the key. Currently, it effectively displays all of the data using console.log("handleTab ...

How to implement a select all feature using React and MaterialUI

I am facing a challenge with managing multiple sets of checkboxes independently along with a toggle that can switch them all on or off within their respective groups. Each checkbox has two states, and I can identify the checkbox being clicked using event.t ...

Date Object Replacement Error: "this is not a valid Date object."

For my web application, I require a specific date value. I attempted to modify the Date prototype, but encountered an issue with Jquery Date recognizing it. InitDate = Date; InitDate.prototype = Date.prototype; Date = function () { if (arguments.leng ...

Finding the Row Number of an HTML Table by Clicking on the Table - Utilizing JQuery

Seeking assistance to tackle this issue. I currently have an HTML table with a clickable event that triggers a dialog box. My goal is to also retrieve the index of the row that was clicked, but the current output is not what I anticipated. //script for the ...

When Firebase authentication signs out users who were previously authenticated, it results in them facing permission denied errors

1) User A visits my website, and A is successfully authenticated and can write to the firebase database through the web browser. 2) User B then visits my site, and after being authenticated, they are able to write to the firebase database via the browser. ...

Organizing an array in JavaScript that includes both version numbers and letters, with each letter representing a specific numerical value

If given an array similar to this one: input = [ "1.1", "1.c", "1.b", "1", "D", "b", "4", "2.1.2", "5.1", "3", & ...

Obtaining the token using django rest framework and ajax - A step-by-step guide

I am in the process of developing a REST API where users can authenticate using tokens. To enable this feature, I have added rest_framework.authtoken to the list of installed apps and made necessary configurations in the settings.py file: INSTALLED_APPS = ...

MUI Autocomplete causing a never-ending cycle of requests

One of the challenges I'm facing involves an Autocomplete component in my code. Here's a snippet of the code: <Autocomplete filterOptions={(x) => x} options={items} getOptionLabel= ...

Error 600: The element you have selected is not a valid target for this action. (Internet Explorer exclusive

I have been developing an AJAX calendar that functions perfectly in Chrome, Safari, and Firefox. However, I am encountering issues with Internet Explorer 9 and earlier versions. The error message I am receiving is SCRIPT 600: Invalid target element for th ...

Is it possible to send an array as a parameter to the Delete() action in a WebAPI using a jQuery Ajax call?

I have been working with WebAPI and successfully implemented a controller method called Delete, using the HTTP verb [HTTPDELETE]. Here is the syntax I used: [HttpDelete] public Resonse Delete([FromBody]Guid[] input) { // code for proc ...

Direct your attention to the final item in a visible array within a ReactJS component

Currently, I'm in the process of developing a chat application using reactjs and am faced with the challenge of adjusting focus to the latest message whenever a new one is added to the array. The structure of my react chat window is as follows: < ...

The Jquery css on my website is not functioning properly

After creating a website feature where clicking on a specific div triggers an onclick event processing a chat_generate function, I encountered some issues. This funciton should insert HTML for the chat into a designated .open_div based on the id generated ...

The Node.js EventEmitter encounters an error stating `listener must be a function` when the `typeof` operator indicates that the value is a function, hint

Dealing with an object that is being interacted with by multiple node.js modules has presented some challenges. My goal is to allow certain modules to add eventListeners to the object. In my codebase, I have an events file where event emitters are attach ...

Using Backbone.js to Retrieve Data from the Server and Bind it to a Model

Having recently delved into Backbone.js, I found this informative tutorial quite helpful in getting started. Now, I am looking to take things a step further by fetching data from the server instead of hardcoding values in JavaScript as demonstrated in the ...

Troubleshooting issues with AngularJS's minDate functionality

I have been trying to set the minDate for the datepicker to today, following the example on the angularJS bootstrap site. However, it seems like something is not working correctly. There are no console errors showing up, but it appears that the minDate is ...

The MUI Module is missing: Unable to locate '@emotion/react'

Attempted this solution, but unfortunately it did not work Currently using the latest version of Material-UI Error: Module not found: Can't resolve '@emotion/react' Let's try installing it then.. npm i @emotion/react @emotion/style ...

Reset the input field upon button press

Is there a way to clear the input field after pressing the button? <div class="form-group autocomplete"> <div class="input-group search"> <input id="search" name="searchterm" type="search" class="form-control form-control search-input" pl ...

What is the correct way to manage a HTTP 408 error in JQuery ajax?

When making a JQuery Ajax call, I encountered an issue where the "error" method did not differentiate between an HTTP 408 error and a normal HTTP 500 error. Upon investigating, I discovered that the jxhr.statusCode was returning as 0 despite the service a ...

Using Node/Express to split the request headers with the .split() method

I am currently working on a way to determine if a specific item exists in the req.headers in order to make a decision on what to send back to the user. Here is my code snippet: function serveAppData(req, res) { console.log("CHECKME", req.headers); //var h ...