angular-spinner | Bypassing error handling for $http.post

Utilizing angular-spinner to display a loading spinner while intercepting all http requests made by my application.

Here is the relevant code snippet:-

//spinner configuration START
        myApp.factory('spinnerInterceptor', ['usSpinnerService', function(usSpinnerService) {
            return  {
                     request: function(config) {
                         usSpinnerService.spin('spinner-1');
                         return config;
                     },
                     response:function(config){
                         usSpinnerService.stop('spinner-1');
                         return config;
                     },
                     responseError:function(config){
                         usSpinnerService.stop('spinner-1');
                         return config;
                     }
            };
        }]);

        myApp.config(['$httpProvider', function($httpProvider) {
            $httpProvider.interceptors.push('spinnerInterceptor');
        }]);
        //spinner configuration END

Aside from managing the spinner, the interceptor just returns the config object.

Issue:-

Despite receiving a 404 error message from one of my POST RESTful endpoints, the success handler within the $http block is still executed. Why is this happening?

$http({
                    method : 'POST',
                    url : url,
                    params :paramsJson,
                    data : _data
                }).success(function(data,status) {
                    // THIS BLOCK GETS EXECUTED AFTER THE SPINNER INTERCEPTOR EVEN WITH STATUS 404 !!!!
                }).error(function(data,status) {
                    // I EXPECT THIS BLOCK TO RUN IN CASE OF A 404 OR ANY NON 2XX RESPONSE
                });

The spinnerInterceptor is being called before the success/error handlers of the $http block, affecting the error handling of the promise returned.

When the spinner interceptor is removed, everything functions as intended.

Any assistance in resolving this is greatly appreciated.

Answer №1

A common issue lies with the "responseError" interceptor. It is essential to reject the request within this block. Otherwise, any error handling already implemented in the interceptor will override whatever you return here and proceed to the success block.

Here is the revised code for the interceptor:

  responseError:function(config){//processing response data
             usSpinnerService.stop('spinner-1');
             return $q.reject(config);
         }

You may find more information on error-handling techniques in Angular at Error Handling in angular.

Answer №2

Implementing an automated spinner feature was a recent task in one of my projects. I utilized $q promises to manage success and error notifications for the interceptor methods, and the implementation ran smoothly. Here is an excerpt from the code:

(function () { 'use strict';

function httpBusyInterceptor($q) {


    function _responseError (response) {                      
        //Code to hide the spinner
        return $q.reject(response);
    }

    function _response (response) {                    
        //Code to hide the spinner
        return response || $q.when(response);
    }

    function _request (config) {                       
        //Code to display the spinner
        return config || $q.when(config);
    }

   return {
        request: _request,
        response: _response,
        responseError: _responseError
    };
}
httpBusyInterceptor.$inject = ['$q'];

angular.module('common.ui').factory('httpBusyInterceptor', httpBusyInterceptor);

})();

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

Sending a form using AJAX causes the page to redirect

I have an input type="file" that triggers a form submission upon change. $(document).on("change", "#image-upload", function (e) { $.ajax({ url: '/BlogPost/UploadHomeReport', type: 'POST', data: $('#upload-i ...

Changing the key of a JavaScript request object into a string variable

Just starting out with programming. The API post call requires an object variable (derived from a variable) to be passed as a string like this: "option": { "235": “30” }, { "238": “32” } In my Angular 6 code: ...

What is the technique for using JavaScript to implement styling on a <td> within an HTML table?

Can someone help me with applying JavaScript to an entire column in an HTML table? Here is the script I am currently using: I want to insert a line break after each comma in the Message column of the table. Can anyone point out what I'm doing wrong? ...

How do you transform data stored in map to string format?

The main objective is to take a large txt file and replace all words according to the information in a csv file. This process will generate a new txt file as well as a new csv file that shows the frequency of each word. I'm currently struggling with ...

creation of cascading drop-down lists

I have been struggling to create a dependent dropdown list using ajax and php, but unfortunately I am not getting the desired outcome. Below is my ajax code: <html> <head> <title>findperson</title> <script type="text/javascript ...

What could be causing the format to be incorrect?

docker run -it -v "%cd%":/e2e -w /e2e cypress/included:6.2.1 --browser chrome When attempting to execute this command within Visual Studio Code, an error is encountered: docker: invalid reference format. See 'docker run --help' Vario ...

How can I prevent webpack from showing the default output after a module build error occurs?

Having difficulty figuring out how to prevent webpack from displaying an error message like the following when encountering a SyntaxError. throw new Error("Module build failed: SyntaxError: ...) Ideally, I'd prefer it not to show any output at all i ...

If an element contains a specific class, then set its display property to none

I am attempting to utilize the hasClass method in JavaScript to determine whether a div should be hidden (display: none) or kept visible as usual. Below is the snippet of code I currently have: if (!$('cool').hasClass('hot')) { ...

Is it possible to make the home page of a Next.js app in a subfolder with basePath accessible outside of the basePath?

My Next.js application is running in the '/portal/' folder and basePath has been configured as: module.exports = { basePath: '/portal' } Now, I want the index page of the application to be accessible at the site root (without baseP ...

When used simultaneously, two jQuery functions fail to operate as expected

Currently in the process of coding my portfolio, I encountered an issue with incorporating two JavaScript/jquery codes together. Firstly, for the first section to be a full-page scroll using fullpage.js "plugin," and secondly, changing the navbar to be tra ...

What is the best way to send an error back to ExpressJS from middleware?

Utilizing [Multer][1] as middleware for handling multipart form data, I am taking advantage of the configuration options it provides through diskStorage. This feature allows for error checking and control over file uploads within Multer. The structure of ...

Authentication with AngularJS and Java, managing $scope

My current system setup includes: front-end = AngularJS back-end = Java EE7/REST-API Both applications are operating on Wildfly 8.2 using Undertow as the application server. One of my main concerns is about the authentication process: Should I impl ...

Using Javascript to populate textboxes with the value of checkboxes

Within my web application, there is a series of checkboxes that, when selected, populate a textbox located above them. If more than one checkbox is checked, their values are displayed in the textbox separated by commas. These checkboxes are structured as ...

Receiving a Promise<fullfield> as a result

I have a situation where I am adding several promises to an array: const apiCallsToMake = []; apiCallsToMake.push(this.getDataFromUnsplash(copyInputParams)); apiCallsToMake.push(this.getDataFromPexels(copyInputParams)); apiCallsToMake.pu ...

Utilizing an event emitter to read from a text file

I have a text file with multiple lines containing data such as pepperoni pizza, pizza margherita, etc. I am trying to create an EventEmitter that will trigger specific events based on the content of the file. For example, if the word "pepperoni" is found ...

Interacting Between PHP and Javascript

<form action="../"> <select onchange="window.open(this.options[this.selectedIndex].value,'_top')"> <option value="">Choose a zipcode </option> <option value="92507">92507</option> <option value=" ...

"I am eager to showcase the text upon pressing the Enter key, implementing an Immediately Invoked Function Expression

My input text box is supposed to store and display the output in an unordered list format when I hit enter. The function works fine without IIFE using onclick event, but it's not working with IIFE. Can anyone assist me with this issue? <html> ...

Convert SVG to image using a personalized icon font

I'm facing a challenge that I hope someone can assist me with: My objective is to save an inline SVG as a PNG image. The issue arises from the fact that the SVG contains foreignObject elements with webfont icons (including Fontawesome and custom one ...

My goal is to develop a program that generates a tree structure from an array of objects

I am looking to transform an array of objects by renaming specific keys and removing certain key-value pairs at each level. Here is the initial input: { "node": [ { "nodeName": "Clothes", "nodePath&qu ...

Numeric Input Box: Show gaps

I have numeric input boxes in my HTML/PHP/JS application where users will be entering numbers with 4 to 7 digits. However, I want the users to see spaces between every third digit for better readability. For instance, User types: 8000 Us ...