Promise Chain Error Handling

There can be two categories of errors in a promise chain.

  • Mistakes coming from the promise chain (using .catch)
  • Mistakes in setting up a promise chain

My question is how best to deal with the latter.

For example, the following .catchwill not catch exceptions thrown foobefore he has the opportunity to return a promise.

function go() {
    return foo()
        .then(bar)
        .catch(bam);
}

Clearly, I can wrap the contents goin a block try-catch.

But would it be better to return the immediately rejected promise from the catch block footo “API support” and have a promise-based interface for all possible events?

+4
source share
4 answers

foo ,

Promise.resolve()
    .then(foo)
    .then(bar)
    .catch(bam);

, foo , bam .


foo,

function promiseWrapper(func) {
    try {
        return Promise.resolve(func());
    } catch (e) {
        return Promise.reject(e);
    }
}

foo,

function go() {
    return promiseWrapper(foo)
        .then(bar)
        .catch(bam);
}
+1

:

function foo() {
    try {
        // some staff which should return promise
    }
    catch(e) {
        retrun Propmise.reject('the reason');
    }
}

function go() {
    return foo()
        .then(bar)
        .catch(bam);
}

foo.

+1

( 3) async. , , .

(async () => {throw new Error})().catch(::console.error)
+1

foo, foo . :

function foo(){
  throw new Error("booom");
  return Promise.resolve(42);
}
function bar(v) { console.log("I am resolved with " + v())}
function baz(v) { console.log("I am rejeceted because of a " + v)}

function go() {
    Promise.resolve(foo)
           .then(bar)
           .catch(baz);
}

go();
Hide result
0

Source: https://habr.com/ru/post/1648241/


All Articles