Skip to content Skip to sidebar Skip to footer

Processing Errors In Promises

I try to figure out how to proper handle errors in promise chain. There are few promises and one of them throws error. In case of error I would like to terminate function in chain.

Solution 1:

That's not how Promise chains work. Promises will only chain correctly if you explicitly return a Promise out of every function invoked in your .then() blocks. If you don't return a Promise out of these functions, the next .then() block is immediately invoked.

You probably want to do something like this:

functionrun() {
    test()
        .then(function (data) {
            console.log("w3", "Print data: " + data);
        });
}

functiontest() {
    returnask()
        .then(function (result) {
            returnreply();
        })
        .then(function (data) {
            console.log("w3", "Finish test");
            returnPromise.resolve(data);
        })
        .catch(function (error) {
            console.log("Hey an error was thrown from somewhere");
            if(error instanceofUnexpectedAskError) {
                //handle specific error logic here. 
            }
        });
}

functionask() {
    console.log("w3", "ask");
    returnPromise.reject(newUnexpectedAskError("Ask threw an error"));
}

functionreply() {
    console.log("w3", "reply");
    returnPromise.resolve("World!");
}

Notice how the ask function returns a specific type of error? You can do something like that if you need to perform different error handling based on which function threw an error.

To specifically answer the questions you asked:

  1. The above method of chaining promises will prevent the next .then() being called if an error is thrown by the previous function.
  2. The above method of chaining will ensure that your .then() blocks are called in the order specified. As long as every .then() is a function, and every function returns a Promise, either through constructing a new Promise(function(resolve, reject)) or through Promise.resolve or Promise.reject, the chain will execute in the correct order.

Solution 2:

You just catch at the end of the chain. If there's any error. It will ignore the other then and go direct to catch.

functiontest() {
    returnnewPromise(function(fulfill, reject) {
        ask()
            .then(reply())
            .then(function(data) {
                console.log("w3", "Finish test");
                returnfulfill(data); // <= Make sure to return here// TODO finish data
            })
            .catch(err =>console.log("w3", "Process error from reply: " + err))
    });
}

Make sure to return Promise or else it won't catch your error.

fulfill(data); should be return fulfill(data);

Post a Comment for "Processing Errors In Promises"