Retrieving the server's response with Angular's interceptor when handling a response error

I recently developed an interceptor Service using angularJS to capture any errors from API calls and manage general error handling like this:

$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  return {
   'responseError': function(rejection) {
      alert("An issue occurred");
      return $q.reject(rejection);
    }
  };
});

It works perfectly, and my server returns the following response on error with a status of 409:

{
message: "Email is already in use",
success: false,
token: ""
}

How can I access this response within the responseError interceptor?

Answer №1

Here's a way to accomplish this task:

$httpProvider.interceptors.push(['$q',  function($q) {
        return {
            'request': function (config) {
               //insert your request logic here
                return config;
            },
            'responseError': function(response) {

                console.log(response);
                if(response.statusText){

                    alert(response.statusText)
                }else{
                    alert("Server down")
                }
                if(response.status === 401 || response.status === 409) {
                    //insert your response logic here
                }
                return $q.reject(response);
            }

        };
}]);

})

Answer №2

$provide.factory('customHttpInterceptor', function($q, serviceA, serviceB) {
  return {
   'responseError': function(rejection) {
      if(rejection.status === 409) {
          //fetch the error message from rejection.message/rejection.data.message and handle it accordingly
      }
      alert("An error occurred");
      return $q.reject(rejection);
    }
  };
});

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

What method sits snugly between prepend() and append()?

Just a quick question I have. I am attempting to align an element with my target. Usually, we use prepend (before the target) and append (after the target). Is there something similar that allows us to position that element directly on top of what we are ...

Magnific Popup is causing a glitch in my Ajax cart slider, preventing my code from functioning properly

Currently, I have implemented an Ajax cart slider that slides from right to left whenever an item is added to the cart. Customers are given the option to add a product with an image to their cart and can view the image directly from the cart by clicking on ...

Can you tell me the name of the Javascript "protocol" or "custom" being referred to here?

From what I can gather, the requests array seems to consist of functions with unique formatting and syntax. However, I'm struggling to find relevant search terms to help me better understand it: var requests = { rewardPoints: function(cb) { io ...

Tips for modifying hover effects using jQuerystylesheet changes

I attempted running the following code snippet var buttonElement = $('<button>Button</button>'); $('body').append(buttonElement); buttonElement.hover().css('background-color', 'red'); Unfortunately, the ...

The AJAX call is not being identified correctly

I am facing an issue with my search result pagination wherein the page reloads instead of loading via AJAX when using the pagination. The search results are correctly loaded through partial view with AJAX, but the pagination triggers a non-ajax request cau ...

Preloader will properly handle websocket connections along with pace js

I recently implemented a preloader on my website built with Ruby on Rails. Everything seems to be working perfectly, except for the fact that due to Pusher websockets, the preloader does not stop and keeps running indefinitely. I attempted to address this ...

How will SEO be impacted if content is concealed using jQuery or JavaScript?

I'm currently developing a web application template for support documentation. While most of the content will be initially hidden to streamline the design, I am considering incorporating detailed descriptions to enhance SEO. These descriptions would b ...

The Server Side Rendering in (Vue+Express) faltered due to inconsistencies in hydration

While browsing Vue's official website, I came across a concise example demonstrating how to implement server-side rendering (SSR) using Vue. (https://stackblitz.com/edit/vue-ssr-example-qaztqn?file=package.json) Intrigued by this example, I decided ...

Generate a random word using Typed.js

Can Typed.js generate a random word for output? $(function(){ $(".element").typed({ strings: ["Lorem", "Ipsum", "Dolor"], typeSpeed: 0 }); }); The output should be one of the following words. (Lorem / Ipsum / Dolor) ...

What methods are available to gradually increase a counter until it reaches a specific number by a designated date?

I have a unique idea for my website - I want to create a special counter that gradually increases to a specific number, but does so over the course of an entire year. Imagine starting at 0 and aiming to reach 35340340 after exactly one year has passed. It ...

Issue with Three.js: real-time color updating for mesh not functioning

Attempting to create a simple program with an animation that switches the color of a traffic light from green to red and back every 2 seconds, but the color change is not working as expected. I have tried debugging the code by printing the booleans that s ...

Managing the Navigation Bar

I am currently using Bootstrap and ReactJS, and I am facing an issue where the active tab on the navigation bar does not change when I scroll down the page. At the moment, the active tab only changes when I click on a specific section. Each section corresp ...

"Exploring the process of animating a mesh in three.js that was generated outside of the init

Currently diving into the world of three.js, I'm eager to grasp the concept of animating a mesh that was created by a function outside of the usual init() method. In my experiments, I've successfully managed to create and rotate a cube within th ...

What methods can I utilize to increase the speed of my JavaScript animation?

Recently, I implemented a Vue component designed to loop a div over the X axis. While it functions correctly, I can't help but notice that it is consuming an excessive amount of CPU. I am interested in optimizing this animation for better performance. ...

AngularJS - the factory is a blank canvas ready to be filled with functionality

Just starting out with AngularJS and running into a bit of trouble. I keep getting the error message mainDataService.refreshStatus is not a function within the $scope.clickMe function. Even though I've initialized the mainDataService variable as an em ...

Tips for utilizing window.scrollTo in tandem with react/material UI?

I have a simple functional component that displays an alert panel with an error message under certain conditions. The issue I am facing is that when the alert panel is rendered due to an error, it might be off-screen if the user has scrolled down. To addre ...

The POST request from the form is returning a null value

I am currently facing an issue with using post in Express and BodyParser to insert data from a form in an EJS file into MySQL. The data keeps returning null, indicating that it is not being parsed correctly from the form to the backend. Can anyone offer as ...

How to extract the HTML content from specific text nodes using Javascript

I have a piece of HTML that looks like this: <div id="editable_phrase"> <span data-id="42">My</span> <span data-id="43">very</span> <span data-id="1">first</span> <span data-id="21">phrase< ...

Step-by-Step Guide on Uploading a File with a Basic jQuery-AJAX Request

I'm in need of a straightforward client-side script for ajax file uploading. I searched the web for such a script, but all I found were plugins with numerous features. I just want a simple ajax file upload script. Is it possible to create something l ...

Display varying information depending on the option class, rather than its value

On my website, I have multiple forms structured like this: <form action="" method="post"> <input type="text"> <select name="a"> <option class="hide-all">Choose</option> <option class="show-link">Show link</option ...