Creating a custom HTTP interceptor that can intercept a response and handle errors within the 'response' property

My setup includes a basic Angular http interceptor designed to manage errors. I need to verify if the received data is categorized as a string, treating it as an error rather than a success.

'response': function(response) {
    if(typeof response.data === 'string') {
        response.status = 422;
        return $q.reject(response);
    } else {
        return response;
    }
},
'responseError': function(rejection) {
    return $q.reject(rejection);
}

Currently, when the data is identified as a string, it enters the appropriate if statement, changes the status, and returns. However, Angular doesn't interpret this as an error. In my http function, it doesn't trigger either the success or error callbacks. When the API sends back a genuine error, it correctly goes into 'responseError' and executes the error callback as expected.

$http({
  method: 'POST',
  url: "http://mydomain/api/login",
  data: $.param({
     username: "test",
     password: "test"
  }),
  headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(successCallback(response), errorCallback(response));

How can I modify my interceptor to return an error that Angular can identify in order to activate the error callback from my http function?

Answer №1

To address this issue, one should create a factory for handling common AJAX responses and errors. This factory can be injected into the system's configuration as shown below:

// Angular factory in separate file and include it in your index.

angular.module('yourApp').factory('myHttpInterceptor', function($q, $location) {
    return {
        // optional method
        'response': function(response) {
            // do something on success
            if(typeof response.data === 'string') {
                response.status = 422;
                return $q.reject(response);
            } else {
                return response;
            }
        },

        // optional method
       'responseError': function(rejection) {
          // handle errors here
          return $q.reject(rejection);
        }
    };
});

Next, intercept the configuration in your app.js file:

.config([ '$httpProvider', 
    function($httpProvider) {
       $httpProvider.interceptors.push('myHttpInterceptor');
} ])

This approach has proven effective for me.

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

Experiencing the issue of receiving `undefined` when trying to access res.query with a JSON query string using

Utilizing qs for constructing JSON-based query parameters for my REST API request: On the client side: import qs from "qs"; let query = { dateTime: { $gte: 1664557995000 } }; let q = qs.stringify(query); let url = "http://lo ...

Encountering the error "TypeError: Unable to access property 'controls' of undefined" when utilizing formArray in Reactive forms

Hi there, I am currently working on creating a dynamic form using formArray in Angular. However, I have run into an issue with the error message "TypeError: Cannot read property 'controls' of undefined." import { Component, OnInit } from ' ...

pre-iframe loading function

Is it possible to capture the state of an iframe while data is loading? The onload event only fires once all content has finished loading. I would appreciate any assistance with this issue. Thank you. ...

Bidirectional binding of attributes in an Angular directive

I have developed a custom Angular Directive known as evoEventMirror. Its main purpose is to attach a jQuery event to an inserted element and apply a specified CSS style to the "root" element. Refer to the example below: <div id="#mydiv" evo-event-mirro ...

Why is my Angular 2 service not showing up in my application?

Trying to access a JSON file using an Angular service has been unsuccessful. While I can easily read and bind the JSON data without the service, attempting to do so with the service results in an error message: Failed to load resource: the server responde ...

Exploring Netbeans 7.3 for Enhanced JavaScript Autocomplete with Parameters

Ever since the upgrade to netbeans 7.3, I've encountered an issue where netbeans no longer automatically provides me with parameter names. For instance, When I see "methodA(param1, param2) xxx.js" in the autocomplete pop-up, clicking on it or pressi ...

"Implementing a feature in Django that clears the input field upon clicking the clear button

I am working on a Django HTML file that includes an input field and a clear button. I need to clear the input field when the clear button is pressed. Is it necessary to use JavaScript for this task, or is there another way to achieve it? <form> ...

Tips on personalizing chosen date formats within the Mantine DatePicker?

I've integrated the Mantine DatePicker into my web application and now I want to customize the default style for when a user selects a date. Here's the current style: https://i.sstatic.net/hjQOi.png This is what I'm aiming for: https://i ...

What causes the scrollbar to not extend to the bottom when connected to another scrollbar via a JavaScript equation?

I have been working on a code that involves multiple scrollbars that are all linked together. When you move one scrollbar, the other two will move proportionally. However, due to differences in width, the scroller doesn't always reach the end of the s ...

Refreshing the page to dynamically alter background and text hues

I'm currently dealing with a website that generates a random background color for a div every time it is refreshed. I have a code that successfully accomplishes this: var colorList = ['#FFFFFF', '#000000', '#298ACC', &ap ...

What is the best way to transform XML into a two-dimensional array using JavaScript?

I really need to store the array in a variable. Currently, I am utilizing .DataTable for pagination. However, it doesn't support tables generated from XML using JavaScript. Based on this source, I have to convert my XML into a 2D array. Below is the ...

How can I adjust the positioning of labels in Semantic UI React?

Has anyone successfully changed the label position from right side to left? I attempted using float: left but it didn't have any effect. import {Radio } from "semantic-ui-react" <Radio label="in progress" toggle /> https://i.sstatic.net/hNGb6. ...

Guide to creating a nested table with JavaScript

Currently, I am utilizing JavaScript to dynamically generate a table. To better explain my inquiry, here is an example of the HTML: <table id='mainTable'> <tr> <td> Row 1 Cell 1 </td> ...

Programmatically setting properties for elements

I have a question about how to programmatically add a prop to a component in my React project. Here is the scenario: In the render() method, I have the following code snippet: <TextField name="password" va ...

The NodeJS server encountered an issue when attempting to load the JavaScript modules

Hey everyone. I'm currently using Node.js and Express.js for the back end of my web application, but I keep running into issues with the server trying to bind references in the source code. Here's the structure of my app: src/ - static/ - ...

What is the best way to transfer a JavaScript variable value from an HTML page to a Model variable within the controller?

I'm facing a challenge in my HTML page where I need to pass a variable value from the frontend to a Model class in an MVC project. What is the most efficient way to achieve this with minimal code? Here's what I have attempted: Index.cshtml: v ...

Encountering the error message "This expression cannot be invoked" within a Typescript React Application

I'm working on separating the logic from the layout component in my Typescript React Application, but I suspect there's an issue with the return type of my controller function. I attempted to define a type to specify the return type, but TypeScr ...

What is the best way to set up localStorage with a multi-dimensional array

I am struggling with modifying my local storage and it's taking up a lot of my time. Initially, I set it up like this: localStorage.setItem('example','{"data": []}'); It was working fine, but now I need to structure it like the ...

CSS to target every second visible tr element using the :nth-child(2n)

My table has a unique appearance (shown below) thanks to the application of CSS nth-child(2n). tr:nth-child(2n) {background-color: #f0f3f5;} https://i.sstatic.net/1AnDi.png I made some elements hidden on the vID, ID, and MO_Sub tr. <tr style="displa ...

What is the best way to organize a massive file over 10Gb filled with words?

I've been presented with this interview query: You have an input file containing words (which could be a jumble of letters) separated by commas, and the file size is 10 GB or more. Can you devise an algorithm to sort all these words? Keep in min ...