Exploring the concept of $http/$q/promise in Angular

I am struggling to understand when $q/$http should trigger the onReject block.

For example, if I have a simple call like this:

$http.get('/users')
  .then(function(res) {
    return res.data;
  }, function(err) {
    console.log(err);
  });

If I encounter a 500 Internal Server Error, it ends up in the onSuccess block. It seems strange to me because technically I did receive a response? My understanding of promises tells me that this is correct, but having error handling logic in an onSuccess block doesn't feel right.

if(res.status >= 400) {
  return $q.reject('something went wrong: ' + res.status);
}

Should I handle 400+ status codes in the onSuccess block or should I return a rejected promise to ensure the onReject block is executed? Is there a better way to handle this situation that I am missing?

I attempted to handle this in an httpInterceptor, but I was unable to figure out how to return a rejected promise from there.

this.responseError = function(res) {
  if(res.status >= 400) {
    // do something
  }

  return res;
};

Answer №1

Ensure your success block is functioning properly. Test the code and verify that the error block will execute if the error code is greater than 300.

$http.get('/users').success(function(data, status, headers, config) {
    // This function will be executed asynchronously
    // when the response is received
  }).error(function(data, status, headers, config) {
    // This function will be executed asynchronously in case of an error
    // or when the server responds with an error status
  });

Answer №2

One way to approach this issue is by utilizing an interceptor instead of relying solely on your callback function.

To implement this, you can update your $httpProvider configuration in the app.config section with code similar to the following:

$httpProvider.interceptors.push(['$q', function ($q) {
    return {
        request: function (config) {
            //perform necessary actions
            return config;
        },
        responseError: function (response) {
            if (response.status === 401) {
                //handle unauthorized access
            }
            return $q.reject(response);
        }
    };
}]);

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

The server's file URLs are modified within the page source of a WordPress site

I've been attempting to integrate Adsense code into a WordPress blog at demonuts.com. I placed the Google code in the TEXT WIDGET provided by WordPress. However, upon running the website, I noticed that the URLs for .js, .css, or .png files are being ...

TypeError thrown by Basic TypeScript Class

I'm encountering an issue where TypeScript is throwing a TypeError when trying to use the class Literal from file Classes.tsx in file App.tsx, even though they are in the same file. Strangely, everything works fine on typescriptlang.org/play. // Class ...

The conflict between Material UI's CSSBaseline and react-mentions is causing issues

Wondering why the CSSBaseline of Material UI is causing issues with the background color alignment of React-mentions and seeking a solution (https://www.npmjs.com/package/react-mentions) Check out this setup: https://codesandbox.io/s/frosty-wildflower-21w ...

Encountering an issue with HTMLInputElement when trying to input an integer value into a label using JavaScript

script code intext = document.getElementById("intext"); totalin = document.getElementById("totalin"); function myFunction() { var x = document.getElementById("totalin"); x.innerHTML = intext.toString(); } The snippet above shows a JavaScript functio ...

How come the data from the Firebase real-time database is only displaying in the console and not on the page when using Vue.js?

I am encountering an issue while trying to display a value stored in my Firebase Realtime Database using the {{ exams.name }} syntax in Vue. Although I can see the value when I console.log it, it does not render on the page. However, when I attempted the s ...

Creative jQuery hover effects tailored to the size of the viewport

Currently expanding my knowledge of jQuery and encountering an issue with some code. I am trying to incorporate an animation effect (fadeIn/fadeOut) when the user hovers over a specific element. However, if the viewport is resized to below 480px for mobil ...

I'm encountering CORS issues while attempting to log in using guacamole from my React app. Can anyone advise on what might be causing this problem

Having trouble logging into the Guacamole form through a React JS web application. The Guacamole server is hosted on Tomcat server, while the React app is on Node.js; both operating on separate domains. Despite using Nginx proxy on the server, encounteri ...

Include jQuery, jQuery UI, and plugins seamlessly to avoid any version conflicts

My goal is to inject my custom code into a webpage using a bookmarklet. This code requires jQuery, jQuery UI, and additional plugins to be included on the page. I'm aware of the noConflict function, but I have concerns about potential conflicts if ot ...

A guide to updating a particular row and sending parameters with jQuery and AJAX

I am utilizing a JSON response to dynamically display table content. Here is the code I am using to display row values: var rows = ''; for(var i=0; i<response.response.length; i++) { rows += '<tr><td class="country">&ap ...

Creating a stunning HTML 5 panorama with GigaPixel resolution

Interested in creating a gigapixel panorama using HTML 5 and Javascript. I found inspiration from this example - Seeking advice on where to begin or any useful APIs to explore. Appreciate the help! ...

Learn how to create an endless scrolling effect on a static webpage using only pure JavaScript

Looking to achieve an Infinite Page Scroll Effect similar to Twitter without relying on jQuery or any other library, using pure JavaScript. I'm new to JavaScript and need assistance with implementing this effect in search results displayed within a La ...

Express - segregated public directory designed for authenticated/unauthenticated individuals

I have a project built with express.js and I'm looking to split the application into two main sections: One for users who are not logged in (with routes only to / - landing page, /login and /* - error404) The second section will be for authorized us ...

Running system commands using javascript/jquery

I have been running NodeJS files in the terminal using node filename.js, but now I am wondering if it is possible to execute this command directly from a JavaScript/jQuery script within an HTML page. If so, how can I achieve this? ...

Error encountered while running a mounted hook in Vue.js that was not properly handled

I have created a To Do List app where users can add tasks using a button. Each new task is added to the list with a checkbox and delete button next to it. I want to save all the values and checked information on the page (store it) whenever the page is ref ...

Eliminate web address parameter using regular expressions

Looking to remove a specific URL parameter from a given URL. For instance, if the URL is: http://example.com?foo=bar&baz=boo And I want to eliminate foo=bar to get: http://example.com?baz=boo Or removing baz=boo would leave me with: http://exampl ...

I'm experiencing difficulty accessing the correct identification number for my questions on the website

Hi, I'm currently developing a website using Meteor where users can post questions and receive answers. I want to implement a feature that allows users to delete their own questions. When I try to directly pull the ID of the question and delete it, it ...

Receiving a response from an XMLHttpRequest() within a function

I've come across a situation where I have a function called isOnline(), and here's how it looks: function isOnline() { var request=new XMLHttpRequest(); request.onreadystatechange=function() { if(request.readyState==4) { ...

Create a regular expression in Javascript that only matches strings that do not contain any periods

Struggling with setting up an express route for localhost:3000/test and utilizing regex to handle specific URL patterns. Need assistance combining regex with Express params functionality. router.get('/test/:path[\s^.]*$', function () { ...

The command '.' is unable to be executed as an internal or external command, executable program, or batch file when using npm start -- -e=stag -c=it

After executing the command shown below npm start -- -e=stag -c=it An error is generated: ./scripts/start.js -e=stag -c=it '.' is not recognized as an internal or external command, operable program or batch file. What can be done to resolve th ...

What sets $vm.user apart from $vm.$data.user in Vuejs?

When you need to retrieve component data, there are two ways to do so: $vm.user and $vm.$data.user. Both methods achieve the same result in terms of setting and retrieving data. However, the question arises as to why there are two separate ways to access ...