Experiencing a situation which triggers error conditions in AngularJS $http promises?

I have created a service with the following definition:

angular.module('services', ['ngResource'])
    .factory('Things', function ($rootScope, $http) {
    var basePath = 'rest/things/';
    return {
        getAll: function () {
            return $http.post($rootScope.PAGES_URL + basePath + 'getAll/' + window.clientId, {});
        }
    };
});

Now, in another part of my code, I am using this service as follows:

Things.getAll().success(function(things){
  //do something with the things
})
.error(function(err){
  // An error occurred during the request
});

What I want to achieve is the ability to handle an error condition if there is a problem with the data at the service level. For example:

Suppose the data returned is:

{
  status:500,
  message:'There was a problem with the data for this client'
}

In that case, I would like to implement something like this in the service:

getAll: function () {
        return $http.post($rootScope.PAGES_URL + basePath + 'getAll/' + window.clientId, {})
  .throwError(function(data){
    return (data.status && data.status == 200);
  });
}

With this implementation, when the throwError callback returns false, the error() promise will be triggered instead of the success promise.

Does anyone have suggestions on how to make this work?

Thank you!

Answer №1

If you are confident that every request will adhere to the convention where the response data contains a status code, then utilizing an HTTP Interceptor is a logical choice. To implement this, you can establish a service and add it to the interceptor list for the $httpProvider:

.factory("customHttpInterceptor", function ($q) {
    return {
        response: function (response) {
            if (response.data.status && (response.data.status === 500)) {
                return $q.reject(response);
            }
            return response || $q.when(response);
        }
    };
});

You have the option to adjust the === 500 condition to something like >= 400 to handle all types of errors, not just the 500 error.

In your module's .config(), include the following:

$httpProvider.interceptors.push("customHttpInterceptor");

For more information, refer to:

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

What is the correct way to properly import a non-relative path in TypeScript?

Struggling with importing into my TypeScript class. // Issue arises here... import * as Foundation from 'foundation/foundation'; // Everything runs smoothly until the above import is added... export class HelloWorldScene { constructor() { ...

React - verifying properties

Here's a question that I've been pondering. In many situations, we find ourselves needing to check if props are undefined. But what about nested props? For example, let's say we have: this.props.data.income.data1.value.chartData and we wa ...

Issue: Unable to locate the "es2015" preset in relation to the given directory

I encountered an issue while attempting to use babel. Error: Couldn't find preset "es2015" relative to directory webpack.config.js module.exports = { entry: './main.js', ourput: { path:'./', filename:&a ...

How does the scope of functions included in files differ between Javascript and PHP?

Last month, I inquired about a PHP issue involving calling a function in one include file that is defined in a later include file. This problem came up during the conversion of an ASP site to PHP, and now it's resurfacing. It seems like Javascript and ...

How can I locate ThreeJS coordinates within the Panoramic GUI?

While I've dabbled with ThreeJS in the past, I'm currently working on a new project that involves setting up hotspots in a panoramic view. I vaguely recall using the camera dolly tool from this link to visualize camera locations. However, I' ...

The issue persists with the event listener not responding to input key

Can the Keycode that is pressed during the firing of addEventListener input be retrieved? <p contentEditable="true" id="newTask">New task</p> document.getElementById("newTask").addEventListener("input" ...

The "For" loop fails to proceed further once a "readline" question is incorporated

Can anyone help me troubleshoot why my loop is not iterating as expected? I need to read in user input x number of times, but it seems to be getting stuck. I suspect it may have something to do with the inline function I created, but I'm not sure. Any ...

Developing a website with multiple pages using Vue.js CLI allows for

I am struggling to understand how to implement multiple pages in a Vue CLI project. Currently, I have my home page set up with a few components, but I am unsure of how to create additional pages. Should I be creating multiple HTML files where the index.htm ...

Updating a table cell triggers a change in every cell

I have a table with columns and I need to calculate values in other cells when there is a change event on the table. I want to use ng-change so that the changes are seen immediately. However, I am unsure of how to properly utilize ng-model - if it is used ...

Utilize a React function to incorporate an external link

Looking to create a link to Twitter using the href attribute but encountering errors with the atag. Is there an alternative method I could use? In essence, I want to have a picture on my homepage that, when clicked, redirects the user to Twitter. I' ...

Utilizing Literal and Instance Formats in JavaScript

There are two main methods for creating JavaScript objects. The confusion arises in understanding when to use each notation. Below are examples of both literal and instance variables, each holding different values and producing different results when opera ...

Error message in Angular 2: Deletion operation is restricted

I am encountering an issue with the Angular 2 http.delete method. Below is my code snippet: const headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded'}); this.http.delete(ConstVarService.url + 'api/tasks/Usu ...

The JQuery JavaScript function fails to complete its execution

Question: How can I resolve the issue where my PHP file returns a large JSON string with approximately 2000 elements, each having 14 child elements? When using jQuery AJAX to fetch the JSON and populate an ID-identified table, the filling process stops mid ...

Is there a way to send all the results of a Flask database query to a template in a way that jQuery can also access

I am currently exploring how to retrieve all data passed to a template from a jQuery function by accessing Flask's DB query. I have a database table with customer names and phone numbers, which I pass to the template using Flask's view method "db ...

Utilizing datatables.net in Vite and Vue: Troubleshooting the error "Uncaught TypeError: $(...).DataTable is not a function"

I encountered an issue while trying to integrate datatables into my vite vuejs Application. The error message I received is as follows: "Uncaught (in promise) TypeError: $(...).DataTable is not a function" Below is the list of packages I am usin ...

How to prevent multiple instances of setTimeout executing

I am facing a particular issue with my music application development using JavaScript and other technologies. I have analyzed the module architecture in Engine and UI, and the problem seems to be within the Engine Modules. Specifically, I have a main Engin ...

Exploring ways to retrieve boolean values with Angular and PHP

I am currently learning Angular and PHP and I am trying to make some modifications to the tutorial found at . Specifically, I want to change the second value to a checkbox and retrieve its value using both Angular and PHP. However, I am encountering an iss ...

Issue: `Alert` not triggering after clicking on anchor link in AJAX response

Below is the code I am currently working with: $('.ver').click(function(e) { e.preventDefault(); var id = $(this).next().val(); $.post('cotizar_detalles.php', {'id': id}) .done(function(response) { ...

Incorporating the sx attribute into a personalized component

I am currently incorporating MUI v5 along with Gatsby Image in my project. To maintain consistency in my styling syntax throughout the application, I decided to include the sx prop in the GatsbyImage component. This is how I attempted it: <Box compon ...

Why is it that my NextJS public script isn't being bundled?

I am facing an issue with three components interacting and I need help in properly bundling them together. There is dynamic configuration on the page that exists within an inline script A static script located in the public folder which utilizes the dynam ...