Dealing with errors effectively in AngularJS $http requests

What is the best approach for handling connection errors in Angular?

When using the $http POST service:

    dossierService.getDossier(uid)

    .then(function (result) {

        vm.dossier = result.dossier;

    }, function (error) {

        handleError(error)

    });//end dossierService.getDossier(uid)

If a connection problem occurs, an error will be returned:

POST http://192.168.25.1:8080/api/query net::ERR_CONNECTION_TIMED_OUT

How can I display the specific error message to the user to communicate what exactly went wrong?

Answer №1

$http.post("/newPath", {content:"info"}).then(function(response){
    // handle success response
}).catch(function(error) {

  console.log(JSON.stringify(error));
  $scope.errorMessage=error

});

and also on your screen ...

<div ng-if="errorMessage!=null">
    {{errorMessage}} OR {{errorMessage.message}}
</div>

Answer №2

One way to handle HTTP response codes is by creating an object with corresponding messages and using an interceptor to throw errors when needed.

moduleError.factory('HttpErrorHandler', function (){
    return {
        401: 'You are not logged in',
        403: 'You do not have permissions'
    }
});



$httpProvider.interceptors.push(function($q, HttpErrorHandler) {
  return {
   'responseError': function(rejection) {
      console.log(HttpErrorHandler[rejection.status]);
  };
});

If the error pertains to specific operations, handle and launch errors accordingly. For custom errors, you can use a code and message object like:

{
   code: 30002,
   message: 'My custom error message'
}

.

dossierService.getDossier(uid)

.then(function (result) {

    vm.dossier = result.dossier;

}, function (error) {

    if(error.status == 400){
      var my_error = JSON.parse(error.data);
      console.log(my_error.message);
    }

});

This approach seems effective.

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

Exploring the dynamic loading of components within routes

Just starting out with Vue and experimenting with vue-router, I'm trying my hand at dynamically loading components without relying on additional libraries like webpack. So far, I've set up an index page and a router. Upon initial page load, I not ...

`Cannot Get jQuery ScrollTop Function to Work for 2nd Element`

Having trouble with an issue. Let me explain. I implemented a scrollTop Jquery on page load that scrolls down after a delay to prompt user action. However, I'm facing a problem where another scrollTop doesn't work after clicking buttons "#b3,#b3 ...

Using AngularJS to add a third-party module called ngIdle

Below is a controller that I am working with: (function () { "use strict"; var app = angular.module('Demo') .controller('MainController', ['$rootScope', '$scope', '$location', 'curUser',MainC ...

Modify the bootstrap form dynamically in response to the user's input. Update the form layout instantly as the user types, with no need for clicking any buttons

Imagine a scenario where, as soon as you enter your credit card number, the form automatically undergoes a change without requiring a button click, similar to how a credit card logo pops up. The form detects changes instantly after the input field has be ...

Using an Ajax XML object to dynamically set images in a DataList

When making an Ajax call to retrieve an XML response and trying to set image names from the XML on a datalist, I encountered some issues. The code snippet I used for setting the image is as follows: $(".Image", tablex).attr('src', product.find( ...

Exploring Cypress: Leveraging the Power of Variable Assignment

Recently, I encountered an issue while working with a variable in a Cypress each loop. Despite incrementing the variable within the loop, it resets to zero once outside of it. Can someone shed light on why this happens and suggest a solution? Thank you. p ...

Could you assist me in retrieving information from an API request?

I can't seem to pinpoint my mistake, but I know it's there. After the user provides their state and city information and submits it, a fetch request is supposed to retrieve latitude and longitude values. These values are then used in another API ...

What are the reasons behind professional web designers opting for absolute paths over relative paths (like for CSS, Javascript, images, etc.)?

It used to be my belief that everyone utilized relative paths, like /styles/style.css. However, I've noticed that certain renowned web designers (such as and ) prefer absolute paths (http://example.com/styles/style.css). This begs the question - why ...

JavaScript code encounters an error stating "TypeError: n is undefined"

I recently crafted a JavaScript script to accomplish a specific task, and overall it was working smoothly. However, as I attempted to simplify the code for a demonstration here on this platform, I encountered two issues. Unfortunately, during this 're ...

What methods can be used to continuously send data to another web page within my website using XMLHttpRequest()?

As I delve into working with node.js and express.js, my primary goal is to efficiently tackle a specific issue. One of the pages on my website is tasked with receiving location data in latitude var lat and longitude var long. The challenge at hand is to c ...

Using a custom jQuery function within an Angular component class

I have a custom query function that I wrote in a JavaScript file located under the source folder (/src/assets/inlineedit.js) of my Angular application. Here is the content of the file: $.fn.inlineEdit = function(replaceWith, connectWith) { $(this).ho ...

Numerous column pictures that occupy the entire browser screen

I am looking to create a grid of clickable images that expand to cover the width of the browser window without any space on either side. Ideally, I would like each image to be 180x180px in size, but if it's easier they can resize based on the browser ...

Velocity: The initial parameter was not recognized as a property mapping

I've been experimenting with Velocity for animations (without jQuery), but I'm running into an issue where I keep getting this error message: Velocity: First argument ([object HTMLDivElement]) was not a property map, a known action, or a regis ...

The instanceof operator does not recognize the value as an instance and is returning false, even though it

Is there a method to verify the current instance being used? This is what I am logging to the console: import { OrthographicCamera } from 'three'; // Later in the file: console.log(camera instanceof OrthographicCamera, camera); and the result ...

Converting data from Random.org into an integer using JavaScript

I have been working on a small web application to experiment with CSS animations. Although it's functioning, I'm seeking more genuine randomness. To achieve this, I am exploring the use of Random.org. How can I import the output from Random.org i ...

Ajax request not populating controller with data in ASP.NET CORE MVC

`Hello everyone, I'm running into a problem with my colleague's assignment and could really use some assistance. The issue pertains to ASP.NET Core MVC. I have an API Controller for editing student groups. This API Controller receives a GroupView ...

The $translatePartialLoader is not functioning properly when attempting to retrieve the preferred language

In my main app, I have several independent components, each loading its own string files. My goal is to set a preferred language in the main app configuration and have each component use this preferred language. Setting the preferred language: $translate ...

Ways to activate JavaScript on a completely dynamic AJAX ASP.NET website

Encountering a dilemma: I have developed a fully dynamic site with only one update panel on the startpage. All content is generated dynamically through code behind, with different pages as web user controls. The issue arises when attempting to open two d ...

"Combining multiple attributes to target elements while excluding specific classes

My dilemma lies in the following selector that identifies all necessary elements along with an extra element containing the "formValue" class which I aim to omit $("[data-OriginalValue][data-OriginalValue!=''][data-TaskItemID]") ...

When integrating react-router 5 and redux 7, there is an issue where the state is not being reset when navigating to a new route using react-router's <Link

My current setup includes the following versions: `"react-router": "^5.2.0",` `"react-router-domreact-router": "^5.2.0",` I'm unsure if my setup is compatible with React-router 5 as I was using a version prior ...