Vows: proceed to the subsequent error handling process

Can you explain how to properly call the next error function using promise chaining?
I initially believed that placing a return statement within the error function would automatically trigger the next error function.

//This code is executed in a controller
dataService.saveRequest()
     .then(function success(res){
        //This message is logged when the service returns a result
        console.log("finished");
     }, function failure(error){
        //This message should be logged when the service encounters an error, but it's not 
         console.log("error from controller");
     });

//Inside the service function
this.saveRequest = function(){
   return $http.post('rest/request/send-request', someData)
       .then(function(result){
         //The success function in the controller will receive this data as expected
         return result.data;
       }, function(error){
          //However, the following error function is not being triggered
          //We need this error function to execute in the controller
           return error;
       });

};

Answer №1

I used to think that if I put a return statement inside the error function, it would automatically trigger the next error function.

However, returning from the error callback actually indicates that you have handled the error situation and the next step will be the success callback. If you want to pass the error to the next function in the chain, you need to return a rejected promise like this:

dataService.saveRequest()
 .then(function result(res) {
    //This code is executed when the service returns a result
    console.log("Task completed");
 }, function error(error) {
     console.log("Error occurred in controller");
     return $q.reject('Error occurred in controller');
 });

Alternatively, instead of using return, you can choose to throw an error.

Answer №2

Whenever you return a value instead of a Promise in a handler function, it will automatically be wrapped with Promise.resolve. This also applies to rejection handlers, causing your rejection handler to return a resolved promise.

To properly propagate rejection, you must either throw an error or return a rejected Promise:

return $http.post('api/send-data', someData)
   .then(function(response){
     // Executed successfully
     return response.data;
   }, function(err){
       throw err;
   });

Answer №3

In order for the subsequent promise in a chain to fail, you must use return $q.reject(); when returning from a promise. Check out this example on plunker: http://plnkr.co/edit/ABCD12345EFG67890Hij?p=preview

The rationale behind this is that your error handler can potentially resolve the error. When handling an error in your function, unless otherwise specified, a new promise will be returned which resolves the error. Consequently, having the next promise automatically fail is not feasible. It's akin to using try/catch.

By catching and managing the error, it moves to the success handler. If you intend to reject it, you need to explicitly return $q.reject();

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

Validating Credit Card Expiration Dates in AngularJS Form

I recently started learning AngularJS and decided to create a credit card validator. I successfully implemented the Luhn Algorithm in a custom filter, but now I'm facing issues with validating the expiration date as well. The conditions for a valid ex ...

Understanding the application of JSON data can be simplified by following these

I am looking to manipulate dates by either adding or subtracting them, but I am unsure of how to extract the dates from the other data present. var fetch = require('node-fetch'); fetch('https://api.nasa.gov/planetary/earth/assets?lon=100.7 ...

Aggregate array based on specified criteria in ReactJS

Let's consider the following array data: array = [ { id: 1, count: 0.5 cost: 100 user: {id: 1, name: "John 1"}, type: {id: 1, name: "T1"}, period: {id: 1, name: "2021"} ...

Using Vue to change select box data separately

I have a functional select box that is currently sending the selected value to a method when the change event occurs. However, I am wondering about something: Let's say I also want to send the cat_id value at the time of selection (to create an objec ...

Rearrange the layout by dragging and dropping images to switch their places

I've been working on implementing a photo uploader that requires the order of photos to be maintained. In order to achieve this, I have attempted to incorporate a drag and drop feature to swap their positions. However, I am encountering an issue where ...

Learn how to showcase a predetermined option in an HTML select element using Vue.js and Minimalect

I am currently utilizing Vue.js along with the Mininmalect HTML select plugin to showcase a list of countries by their names and values, where the value represents the 2 digit country code. Successfully, I have managed to implement the plugin for selectin ...

Internet Explorer 10 not triggering the 'input' event when selecting an option from the datalist

Within this particular scenario, there is an input field paired with a corresponding datalist element. My aim is to develop JavaScript code that actively listens for when a user chooses an item from the list. Most resources suggest utilizing the "input" ev ...

Dynamically assigning a name to a variable through code

Is there a quicker way to complete these 100 tasks? variable_1 = 1; variable_2 = 2; variable_3 = 3; ... variable_100 = 100; I attempted to use the following code: for(var i = 1; i <= 100; i++) { variable_ + i = i; } However, I encountered an e ...

"Utilizing Angular's built-in functionality to enable drag-and-drop behavior on an element within

Currently, I am working with Angular and JSPlumb. My goal is to bind the draggable behavior from jsplumb to my element in the directive by using the element in the link function. This is how I currently approach it (http://jsfiddle.net/r8epahbt/): // In ...

An issue has occurred in AngularJS where the error message "ng areq not

I'm facing an issue with my meta controller, as I am trying to alter the meta tags dynamically. When checking the console, I encounter the error message error ng areq not a function. I have looked on StackOverflow for similar issues but couldn't ...

Creating a custom Higher Order Component to seamlessly connect react-relay and react-router using TypeScript

Hey there! So, my Frankenstein monster project has decided to go rogue and I'm running out of hair to pull out. Any help would be greatly appreciated. I've been working on setting up a simple app with React, React-Router, React-Relay, and Typesc ...

Locating a specific item using its individual ID within Firebase

One thing that's often overlooked in Firebase tutorials is how to retrieve objects based on their unique IDs. The push() method generates these unique IDs automatically, but the question remains: how do we access the specific object associated with an ...

New update to Angular Currency Filter - Now including Symbol Â!

While utilizing angular's currency filter, I noticed an unexpected extra symbol being outputted: Â. This is the HTML code: {{totals.subtotal | currency}} {{totals.tax | currency}} {{totals.total | currency}} The 'totals' object looks lik ...

Oops! The provided value for the argument "value" is not a valid query constraint. Firestore does not allow the use of "undefined" as a value

I encountered an error while exporting modules from file A and importing them into file B. When running file B, the error related to Firebase Cloud Firestore is displayed. const getMailEvents = (startTime, endTime) => { serverRef = db.collection("Ma ...

The server is indicating that the validation for the user has failed due to the required field "foo" not being provided in the Node.js

An error message was received with the following details: "User validation failed: email: Path email is required., display_name: Path display_name is required." The error name returned is: ValidationError. The AJAX call code snippet is as follows: f ...

Preserving state during navigation and router refresh in Next.js version 13

In the component below, we have a Server Component that fetches and renders data. When router.refresh() is called on click, it reruns the page and refetches the data. However, there is an issue with Nextjs preserving the state. Even though the server compo ...

When trying to access data within objects using JSON iteration, it may lead to encountering an issue of reading a

Attempting to retrieve specific data from a JSON file obtained from a website has proven challenging. While iterating through the collection of objects, undefined values are constantly encountered. Unfortunately, if the JSON is poorly structured, modificat ...

Learn how to dynamically set the "selected" option in Vue based on object data

I've done some digging on SO but haven't found exactly what I need. So, here's the situation - I've got a sorting function in progress. I have an array of date ranges (PayPeriods) that I want to render into a select with option compone ...

Improving a lengthy TypeScript function through refactoring

Currently, I have this function that I am refactoring with the goal of making it more concise. For instance, by using a generic function. setSelectedSearchOptions(optionLabel: string) { //this.filterSection.reset(); this.selectedOption = optionLa ...

Tips for customizing the appearance of a React-Table header when sorting data

How can I change the header's background color in react-table based on a selected item? For example, if I click on ID, the ID header should change its background color to red. I have tried various methods to update the background color upon selection ...