Ben Aston Ben Aston - 4 months ago 13
Javascript Question

Handling errors in promise chains

There are two categories of errors that might occur in a promise chain.


  1. Errors thrown from inside the promise chain (dealt with by
    .catch
    )

  2. Errors thrown when configuring the promise chain



My question is how best to deal with the latter.

For example, in the following
.catch
will not catch exceptions thrown by
foo
before it has had a chance to return a promise.

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


Clearly I can wrap the contents of
go
in a
try-catch
block.

But would it be better to return an immediately rejected promise from a catch block in
foo
to "maintain the API" and have a promise-based interface for all eventualities?

Answer

Alternatively, you can include foo in the chain, like this

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

Now, even if the foo throws, the bam will take care of it.


Or, build a wrapper over foo,

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

And then use it, instead of foo, like this

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