Dealing with errors when making HTTP requests in AngularJS using the `then`

What is the best way to tackle an HTTP error like 500 when utilizing AngularJS "http get then" construct (promises)?

$http.get(url).then(
    function(response) {
        console.log('get',response)
    }
)

The issue here is that for any non-200 HTTP response, the inner function does not get executed.

Answer №1

To improve your code, make sure to include an extra parameter:

$http.get(url).then(
    function(response) {
        console.log('get', response)
    },
    function(error) {
        // Handle any errors here
    })

Answer №2

To enhance the cleanliness of this code snippet, consider implementing this revised form:

$http.get(url)
    .then(function (response) {
        console.log('get', response);
    })
    .catch(function (error) {
        // Address any errors here
    });

Offering an alternative perspective in line with @this.lau_'s response.

Answer №3

Check out the AngularJS documentation for $http service

$http.get(url).then(successCallback, errorCallback);

Make sure to replace successCallback and errorCallback with your own functions.

Note: Although Laurent's answer using then is more accurate, this alternative method is provided for future reference of other users as well.

Answer №4

If you need to manage server errors at a global level, consider setting up an interceptor service for $httpProvider:

$httpProvider.interceptors.push(function ($q) {
    return {
        'responseError': function (rejection) {
            // handle errors here
            if (canRecover(rejection)) {
                return responseOrNewPromise
            }
            return $q.reject(rejection);
        }
    };
});

Documentation: http://docs.angularjs.org/api/ng.$http

Answer №5

Check out this code snippet

function makeHttpRequest(method, url, dataToSend, callback){

        var type = (method === "JSONP")? "jsonp" : "json";
        $http({
                method: method,
                url: url,
                dataType: type,
                data: dataToSend || {},
                cache: true,
                timeout: 1000 * 60 * 10
        }).then(
            function(response){
                callback(null, response.data); // server response
            },
            function(response){
                handleResponse(response, callback);
            }
        );

    }
    
    function handleResponse(response, callback){
        switch(response.status){
            default: callback(response.status + ": " + response.statusText);
        }
    }

Answer №6

I wasn't able to utilize the information provided above, so I decided to share this alternative solution.

$http.get(url)
  .then(
    function(response) {
        console.log('get',response)
    }
  ).catch(
    function(response) {
    console.log('return code: ' + response.status);
    }
  )

You can also refer to the $http response parameter.

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

JavaScript - filter out values not included in specified list of attributes

I am seeking a technique that, when provided with a list of attributes, retains only the values associated with keys present in the list. For instance: attrs = ['a', 'b', 'c'] obj = {'a': 1, 'b': 2, &apos ...

Ways to specify a setter for a current object property in JavaScript

Looking to define a setter for an existing object property in JavaScript ES6? Currently, the value is directly assigned as true, but I'm interested in achieving the same using a setter. Here's a snippet of HTML: <form #Form="ngForm" novalida ...

The text color remains the same even after the method has returned a value

I have a vuex query that returns a list of books. I want to display each book with a specific color based on its status. I tried using a method to determine the color name for each book and bind it to the v-icon, but it's not working as expected - no ...

Ensure that the input button for uploading is only accessible when checked and is marked as

Most of my previous questions have been about input boxes and SQL, as I am still in the learning process. Any help is greatly appreciated. My current question revolves around displaying a button to upload an image using PHP (although for this example, I w ...

Adding a class to individual elements generated through a v-for loop: a step-by-step guide

I have been working on a basic inventory "checker" that generates 14 divs labeled as either "active" or "inactive". Using Vue, I am able to create these divs with a simple v-for loop: <div class="inventory"> <div class="item" v-for="index in 14" ...

Delayed response of text effects in JQuery on page load

Within my rails app, I have the following code snippet: window.onload = -> $("#mycontainer").typewriter() $("#div1").fadeIn("slow") This code snippet interacts with the following block of content: <blockquote class="pull-left"> < ...

Strategies for effectively handling errors in the requestAnimationFrame function

I'm currently facing issues with the animate() function, as it tends to crash my browser and cause my computer to heat up when errors occur. I attempted to use a try/catch handler to handle these errors but it did not work as expected. animate(){ ...

I am noticing multiple quantities of the same item being added to my shopping

Recently, I encountered a problem with my online shop that seems to be related to the Javascript. The issue arises when I add an item to my shopping cart from this particular page: . Initially, when I click 'Add to Cart,' the item is correctly ad ...

Showing additional content in an alternative design

I'm currently facing an issue with the "load more" post button on my Wordpress site. I've designed a unique grid layout for the category page, with a load more button at the bottom. However, when I click the button to load more posts, they appear ...

Sort and categorize JSON data with JavaScript/jQuery using group by and order by

Having some JSON data, I am looking to group by and sort the author names in alphanumeric order. Previously asked this question with no satisfactory answer, so this time I will provide more details. Can someone explain the difference between groupby and o ...

Exploring the power of JQuery's asynchronous promises within a labyrinth of nested

As a newcomer to Node.js and promises (specifically using Q.js), I am attempting to create a web scraper for a site with the following structure: Main Page: contains a list of categories, each with a link leading to a page listing various stores. List of ...

Updating variable values using buttons in PHP and Javascript

I've implemented a like/unlike button along with a field displaying the number of likes. The code below uses PHP and HTML to echo the variable that represents the total number of likes: PHP-HTML: <span>likes: <?php echo $row['likes&apo ...

I possess a pair of items that require merging together while combining any overlapping key values in their properties

I have a scenario where I need to merge two objects and concatenate strings if they have the same key. obj1 = { name: 'John', address: 'Cairo' } obj2 = { num : '1', address: 'Egypt' } After merging, the r ...

Tips for dynamically sending data without explicitly stating the name:

Looking to create a JSON structure with name and value pairs such as name:"john". Check out the code snippet below: var allFields = []; var inputs = document.getElementsByTagName('input'); for(var i=0; i<inputs.length;i++){ name = in ...

Achieving optimal hardware performance for WebGL compatibility is essential

Lately, I have been exploring the world of Three.js to create impressive 3D scenes in WebGL. To ensure compatibility for all users, I have also developed versions using Three's CanvasRenderer which may not be as detailed but can still function on brow ...

Utilizing the comma as a delimiter for lists in AngularJS

I'm trying to generate a comma-separated list of items: <li ng-repeat="friend in friends"> <b ng-repeat="email in friend.email">{{email}}{{$last ? '' : ', '}}</b>... </li> The AngularJS documenta ...

Storing the usernames of users through local storage is essential for data preservation

My instructor mentioned a unique way to store user names using "localstorage" and arrays in JavaScript. This method ensures that the names are saved even if the page is reloaded. Here is the code snippet for achieving this functionality: html: <!doctyp ...

Refresh data on Table with AJAX and a repeated process

I am relatively new to Javascript and Ajax, so please bear with me as I explore... My goal is to update a table after inserting a new row. Instead of generating an entire HTML table through Ajax output, I would prefer to gather data from a PHP MySQL datab ...

`Dealing with Java Servlet Exception in Kendo UI Environment`

I am facing an issue with displaying date in my Kendo UI grid. The data is coming from a Java servlet, and I have set the status code to 500 whenever an error occurs. Although I can see the error on the console, I am unable to handle it in JavaScript. My g ...

Modify the content and display of a stationary div based on vertical positions

I am interested in creating a vertical website that features multiple divs appearing at specific y-points on the page. These divs will contain text and will always be positioned fixed at 20% from the left and about 250px from the top. My goal is to have t ...