Creating a custom AngularJS HTTP interceptor that targets specific URLs

Is there a way to configure an $http interceptor to only respond to specific URL patterns?

For example, I want the interceptor to only intercept requests that match "/api/*" and ignore any other requests.

Answer №1

To manage errors in requests and responses for URLs that begin with "math/", you can filter the URL in both success and rejection functions.

Below is an interceptor example:

$httpProvider.interceptors.push(function($q, mathError) {
    return {
        requestError: function(rejection){                            
            mathError.anyError(rejection);    
            return $q.reject(rejection);
        },
        responseError: function(rejection){                            
            mathError.anyError(rejection);
            return $q.reject(rejection);
        }
    };
});

Here is a factory where you can handle these errors:

myApp.factory('mathError', function(){
    return {
        anyError: function(rejection){ 
            if (rejection.config.url.substr(0, 5) === "math/") {
                console.log("Only Math errors are handled here"); 

                //Implement custom error handling
            }
        }         
    };
});

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

AngularJS Unveiled: The Puzzle of ng-if's Digest Loop

I am experiencing an issue with an infinite loop when loading the view. The data is retrieved from an API using ngResource in the controller. The view is being rendered multiple times before displaying correctly. I suspect that there may be a loop occurrin ...

How can I turn off autocomplete in MUI textfields?

Currently, I am working with the latest version of mui. Within my user contact info form, there is a zip code field that I do not want to be auto completed if the value is null. However, despite my efforts, it continues to autocomplete with the email saved ...

Tips for getting a sticky table header and including a limited number of columns, each with checkboxes or input fields

Encountering issues while trying to implement functionality with a jQuery library. One specific problem is the inability to interact with checkboxes on sticky columns, as well as difficulties clicking and typing in text fields. I am utilizing the jQuery S ...

Having trouble implementing the page object model with cucumber.js: bug detected!

I have been working on implementing a page object pattern in my cucumber.js test automation suite with selenium webdriver. However, I am facing an error when trying to call the page object from my test step. The folder structure I am using is as follows: ...

Can you explain the distinction between using angular.copy() and simply using an assignment (=) to assign values

When a button is clicked, I want to assign certain values using the event parameter. Here is the code: $scope.update = function(context) { $scope.master = context; }; The $scope.master has been assigned the values of user. Recently, I came across th ...

Using Node.js to create a RESTful API that pulls information from MongoDB

I am currently working on creating a REST API using Node.js to retrieve the last N rows from a MongoDB collection. Here is my current code snippet: var express = require("express"); var app = express(); var bodyParser = require("body-pa ...

Creating a ListView in React Native and utilizing the CloneWithRow method with an object instead of an

When retrieving data from a webservice, I am able to work with JSON arrays without any issues. WebServiceHandler.get('http:/api.local/stock',{},{) .then((val)=>{ this.setState({ dataSource: this.state.dataSou ...

Stopping an endless loop in JavaScript by pressing a key on the keyboard can be a useful

I've been working on creating a JavaScript game and am currently tackling the challenge of implementing gravity. One crucial aspect I need to address is creating an infinite loop without causing the browser to crash. Is there a way for me to include a ...

What is the best way to adjust the size of a canvas and then upload the resized information to a

I need to update the user's database table row data with new resized dimensions (changing width and height). For instance: In my online editor, I create a canvas of size 1000x500, add objects, and save -> This data is sent to the database When re ...

Tips for compressing JavaScript on the fly

Is there a method to dynamically compress JavaScript, similar to how gzip functions for HTML (and apparently CSS)? I'm looking for a solution where I don't have to manually compress the file before uploading every time. I want the server to hand ...

Enhancing SVG graphics dynamically with JavaScript and ensuring compatibility across different web browsers

I am currently working on incorporating an element into an existing SVG file. Interestingly, the process runs smoothly on Chrome and Firefox but encounters issues on Edge. I aim for it to function seamlessly on the latest versions of all three browsers, wi ...

jQuery event.preventDefault not functioning as expected

I am attempting to use jQuery's preventDefault() method, but when I submit the form, it still displays the default behavior and reloads the page. Here is the code from index.html: <body> <script src="/socket.io/socket.io.js"></script& ...

What is Angular's approach to handling a dynamic and unprocessed JSON object?

When a JSON file is placed under assets, accessing it using something like http://localhost:4200/myapp.com/assets/hello.json will fetch the JSON file directly without any graphical user interface. This indicates that Angular must be able to return a raw JS ...

Sliding off the canvas - concealed navigation

I have implemented CSS to hide a menu on mobile: #filter-column { position:absolute; left:-400px; } However, I want the menu to slide in from the left when the user clicks a link, and everything else should be hidden. When the layer is closed, th ...

expanding the expressjs res feature

I am currently working on implementing an error and notification feature for my expressjs app. My approach was to add a function by calling: app.use(function (req, res, next) { res.notice = function (msg) { res.send([Notice] ' + msg); } }); ...

JavaScript can be used to arrange a table in both ascending and descending order by simply clicking on the header

window.addEventListener('DOMContentLoaded', () => { let dir = "dsc"; th = document.getElementsByTagName('th'); for(let c=0; c < th.length; c++){ th[c].addEventListener('click',item(c)); } ...

Showing the output variable from node.js on a canvas

Is it possible to display the output of my node.js program, which consists of a series of points (x,y), on canvas without a browser? I came across this module that could potentially help with displaying the points: (https://www.npmjs.com/package/canvas) ...

A particular character is displayed exclusively in a text box using either jQuery or JavaScript

Text Box <input id="txtbo" type="text" value="CAN'T TOUCH THIS!" size="50" /> Solution Using jQuery or Javascript: var readOnlyLength = $('#txtbo').val().length; $('#txtbo').on('keypress, keydown', function(even ...

Material User Interface, MUI, Modal, Back to Top Scroll按钮

After spending some time experimenting with scrollTop and the Dialog component (a fullscreen fixed modal) from Material-ui, I found that I couldn't quite get scrollTop to function properly. Whenever I clicked the "go down" button, it would either retu ...

progressing both forward and backward through every month

I am currently working on a project that involves creating a calendar using JavaScript. I have implemented functionalities where I can navigate back and forth through months, fetching the days within each month. However, I am facing an issue where if I go ...