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

Error possible in modal due to interaction between JavaScript, PHP, and Bootstrap - Unable for PHP file to successfully retrieve value from JavaScript file

I have an existing database that is already populated. Additionally, I have a JavaScript function that captures the ID of the element when a button is pressed. Here's an example: Name of Subject | Actions -------------------------------------- ...

Display various MongoDB datasets in a single Express route

I currently have a get method in my Express app that renders data from a MongoDB collection called "Members" on the URL "/agileApp". This is working fine, but I now also want to render another collection called "Tasks" on the same URL. Is it possible to ...

Guide on retrieving POST data in sveltekit

Hello, I'm new to sveltekit and I am trying to fetch post data in sveltekit using a POST request. Currently, I am utilizing axios to send the post data. const request = await axios .post("/api/user", { username, email, ...

Did I incorrectly associate the function with the button causing it to always be executed?

I am working on a PHP page, where I have some initial content followed by session initialization code: <?php session_start(); ?> The requirement is to display a disconnect button only if the user is logged in, indicated by the presence of $_SESS ...

MySQL conditions in game development

When a player transfers an item to their character, the item type is communicated to the server. In scenarios where a player equips an armband with the type "bracelet," I want it to attempt placing the item ID in the leftbracer column of the game_moblist ...

The consequences of jQuery Ajax Memory Leaks

After reading through several other posts on the topic, I have noticed a memory leak issue when making repeated ajax calls with jQuery (every 30 seconds in my case). Switching from using $get to $post helped reduce the size of the leak, but it still occurs ...

It is not possible to import node_modules within an electron worker process

Question I'm currently experimenting with using web workers within an Electron application. I have been successful in creating the worker process from the renderer process, but I am encountering a crash when attempting to use require('some_modul ...

The duration from when the Ajax request is sent to when the response is received results in

Has anyone experienced strange results when measuring the time between sending and receiving an ajax request? Sometimes I get negative values. Can someone shed light on this peculiar behavior? var before = 0; var after = 0; $.ajax({ url: 'data.ph ...

Learning to control the JavaScript countdown clock pause and play functionality

How can I control the countdown timer to play and pause, allowing me to resume at the exact time it was paused? At the start, the timer is set to play. Please keep in mind that the button appears empty because the font-awesome package was not imported, b ...

Code functions properly on local host but encounters errors when deployed to live server

My comment system was working fine on localhost using PHP, AJAX and JavaScript. However, after transferring my website to a live server, the code does not seem to be functioning properly. Here is an example of the script: <script type="text/javascript ...

The Magic of Javascript Routing with Regex Implementation

I'm currently developing a Javascript Router similar to Backbone, Sammy, and Spin. However, my specific requirements are rather straightforward. I need the ability to define a series of routes along with their corresponding callbacks, and I want to be ...

Error in Mongoose validation: "Please provide a value for the 'first' field and the 'last' field."

Another user has previously posted a similar question, but I'm still struggling with my MongoDB website. I am working on a project to store names using mongoose. Here is the code for my routes and models: const router = require("express").Router(); c ...

What is the best way to discover all available matches?

By utilizing this code snippet, I am able to locate text between specific start and end words. However, the search process stops after the first pair is found. Is there a way to identify all matches? const file = fs.readFileSync('./history.txt', ...

Issue: The module '[object Object]' could not be located

const express = require('express'); const app = express(); const jade = require('jade'); const path = require('path'); const server = require('http').createServer(app); const io = require('socket.io').liste ...

Exploring user inputs and displaying variables using JavaScript and HTML 4.01

I was testing some code and I'm facing an issue that I can't figure out: <HTML> <head> <title> Page 1 </title> <script> function myFunction() { var x=document.getElementById("myEmail") document.write(x) } </scr ...

Is it within the realm of possibility for a route-handling function to accept more than two parameters?

Recently, I started learning about node js and delved into the world of jwt authentication. While going through some code snippets, I came across a request handler in express that caught my attention. app.post('/login',function(req,res){...}); ...

Using the code `$("img").one('load'` can trigger only a single load event without repetition

I have implemented the following function: function CheckImage(url, index) { $("<img/>").one('load', function () { $("div.photos").append(this); }).attr('src', url).attr('data-photo', '0' + ind ...

Guide to automatically update div with new table rows with the help of Ajax

Can you assist me in updating the div called "table" that contains a table fetching rows from the database? <div id="table"> <h1 id="Requests"> <table></table> </h1> </div> <button id="refresh-btn"&g ...

The React JSX error message "Maximum update depth exceeded" occurs when there

It appears that I am facing an issue of creating an infinite loop while passing props from one class to another. Despite ensuring that the buttons are correctly bound and trigger only once, the problem persists without any solution in sight after thorough ...

Is there a more efficient method for implementing server side rendering in a Next.js application?

Currently, I am implementing server-side rendering in my Next.js application. This specific component is responsible for returning HTML content. I'm wondering if there are more efficient methods available? import Feature from 'components/home/Fea ...