Error functions in Angular HTTP Interceptor are not being triggered

I followed the example code for an interceptor from the Angular HTTP documentation, but I am having trouble getting the "requestError" and "responseError" functions to trigger. The "request" and "response" functions are working as expected.

myApp.config(['$httpProvider', function ($httpProvider) {
        $httpProvider.interceptors.push(function ($q) {
            return {
                'request': function (config) {
                    return config; //this is called
                },

                'requestError': function (rejection) {
                    return $q.reject(rejection); //this is not called
                },

                'response': function (response) {
                    return response; //this is called
                },

                'responseError': function (rejection) {
                    return $q.reject(rejection); //this is not called
                }
            };
        });
    }]);

When making a request to the server and receiving a 400 error, none of the error handling functions in the interceptor seem to be triggered. The service being used is shown here:

User.publicProfileGetProfile = function (value, type) {
    return $http({
        url: '/public/profile/' + type + '/' + value,
        method: 'GET'
    }).then(function (response) {
        return response;
    }, function(error){
        return error;
    });
};

The issue seems to be with the handling of errors and responses within the interceptor. I'm seeing that when a 400 error occurs, it is coming back as 'undefined' through the "response" function instead of triggering the appropriate error handler. Any insights on what may be missing or incorrectly implemented would be appreciated!

Please let me know if any crucial details were left out.

Answer №1

When you utilize the return statement, the error handler transforms the rejection into a success outcome. It is advisable to make use of throw instead in order to properly chain the rejection.

User.publicProfileGetProfile = function (value, type) {
    return $http({
        url: '/public/profile/' + type + '/' + value,
        method: 'GET'
    }).then(function onSuccess(response) {
        return response;
    }, function onReject(error){
        // Using return changes rejection to success
        //return error;

        // Use throw for chaining rejections
        throw error;
    });
};

Answer №2

After confirming that the JSFiddle (by @georgeawg) was functioning correctly, I double-checked to ensure mine mirrored it exactly. Once I realized there was an issue, I investigated if any other interceptors were causing trouble. It turned out that another interceptor was triggering first and sending errors as responses, followed by this one processing them as successful responses. Removing the problematic interceptor resolved the issues, and everything is now operating smoothly!

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

Programmatically simulate a text cursor activation as if the user has physically clicked on the input

I have been attempting to input a value into a text field using JavaScript, similar to the Gmail email input tag. However, I encountered an issue with some fancy animations that are tied to certain events which I am unsure how to trigger, illustrated in th ...

Unable to retrieve the text enclosed between the:: before and after the:: marker

I attempted this using the XPATH finder in Chrome, and it highlighted the element. However, when running my Selenium script, I received the following error: Caused by: org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: ...

"Is it possible to move the text on the canvas by dragging it to where you want it to be

Seeking help again after an unsuccessful attempt. How can I allow the user to add text to the canvas by dragging it to their desired location? For example, if they input text somewhere, it should appear on the canvas and then be draggable to any position ...

Typescript - unexpected behavior when using imported JavaScript types:

I am struggling with headaches trying to integrate an automatically generated JavaScript library into TypeScript... I have packaged the JavaScript library and d.ts file into an npm package, installed the npm package, and the typings modules in the TypeScr ...

Encountering the "ERPROTO" error message while attempting to send an Axios request from my REST API

I have set up my API at "localhost:3000/api/shopitems" and it successfully returns the JSON data below when accessed through a browser: [ { "item_available_sizes": { "s": 1 }, "imgs": { "album": [], ...

What steps can be taken to reset the redis database when the nodejs server disconnects?

I have created a basic chatroom application using a node express server. This application relies on a redis database for storing the nicknames of all connected clients. Now, I am looking to implement a feature that clears the redis SET named members when ...

Troubleshooting a Heroku build failure in Node.js due to issues with the Mongodb module

While deploying my app on Heroku, I am facing an issue. My app uses Express and Mongodb. Even though the repository works fine during local development, when deployed on Heroku, there is an error in the logs related to the Mongodb module itself. How can I ...

When the function $(document).width() is called, it may yield varying results depending on the timing of the call

Every time I use $(document).width(); within $(window).load(function(){}) or $(document).ready(function(){}), the result differs from when it is called inside $(window).resize(function(){}). The discrepancy is approximately 100px, and it's not due to ...

Is there a different method I can utilize to create a conditional statement for assigning a value in JavaScript?

I have this code snippet that seems a bit unclear to me: if (!app.config.admin.examStatusId) { app.config.admin.examStatusId = exam.examStatus.dataPlus[0].id; } Do you have any suggestions on how I could rewrite this more clearly without using an if s ...

React - callbackFromApp function is executing only one time when clicked

Whenever I click a button within my child React module, it is meant to increment the timer and then pass back the timer in minutes and total seconds to the parent component where it will be stored as state. The issue I am facing is that when I click the b ...

Error in MUI: Unable to access undefined properties (reading 'drawer')

Recently, I encountered an unexpected error in my project using MUI v5.0.2. Everything was working fine just a week ago with no errors, but now I'm facing this issue without any changes made to the code: Error: TypeError: Cannot read properties of un ...

Using AngularJS to handle click events and blur events

I am attempting to dynamically change the class based on user interaction in my code. The class should switch between "large" and "active" depending on whether the input field is filled or not. Please see the modified script below. <div class="snippe ...

Splitting an array into multiple arrays with distinct names: A step-by-step guide

I have a data set that looks like this: [A,1,0,1,0,1,B,1,0,0,1,A,1]. I want to divide this array into smaller arrays. Each division will occur at the positions where "A" or "B" is found in the original array. The new arrays should be named with the prefix ...

React - Utilizing Secondary Prop Value in Material UI Node Components

I've been working on streamlining my code and am wondering about the best way to pass an additional value using props while fetching data from the backend. I'm utilizing material UI's Autocomplete with the PERN stack. Everything is functioni ...

Having trouble getting a constructor to function properly when passing a parameter in

Here's the code snippet I'm working with: import {Component, OnInit} from '@angular/core'; import {FirebaseListObservable, FirebaseObjectObservable, AngularFireDatabase} from 'angularfire2/database-deprecated'; import {Item} ...

Secure User Verification in Laravel 5 and AngularJs sans the need for JWT Tokens

I am currently working on a project that involves utilizing a Laravel-based back-end and a front-end built with both Laravel and AngularJS. After completing 40% of the back-end development, I am now faced with the task of implementing the front-end. Howev ...

Obtain information from express middleware

I am currently working on a project using node.js. As part of my application, I have developed a middleware function that is triggered whenever a GET request is made. This occurs when someone visits the home page, profile page, or any other page within my ...

NestJS is having trouble importing generated types from the Prisma client

When working with Prisma in conjunction with NestJs, I encountered an issue after defining my model and generating it using npx prisma generate. Upon importing the generated type, I can easily infer its structure: import { FulfilmentReport, FulfilmentRepor ...

Executing a npm script (script.js) with custom arguments - a step-by-step guide

I'm considering creating a setup similar to lodash custom builds. Basically, I want to allow users to input a command like: lodash category=collection,function This would create a custom module with the specified category. I've been looking in ...

Exploring the power of V-for with checkboxes in VueJS

One issue I am facing is related to triggering my save method only when a checkbox is selected or true in Vue JS. I have no problem listing values and saving them to the database using axios, Vue JS, and Spring Boot. However, every time I click the checkbo ...