1
votes

As outlined by this SO post and answer, it is customary to throw an error from the catch statement that resides inside an async/await function like so:

} catch (error) {
    throw new Error(400);
}

As highlighted by that same post, you typically wouldn't return a rejected promise (see below) since it's a semantic mis-match with 'try-catch' statements.

} catch (error) {
    return Promise.reject(new Error(400));
}

By that same logic, should I be returning rejected promises when returning errors outside of catch statements from my async/await function instead of throwing them?

In other words is the following semantically inconsistent with the above logic?

async function promise () {
    throw new Error('Some error');
}

And, is this the preferred way of returning an error inside an async/await function since async/await functions implicitly return a promise?

async function promise () {
    return Promise.reject(new Error(400));
}

I'm aware both of the above snippets allow errors to be caught when consuming the promise.

1
IMO, you just throw the error. It doesn't matter whether you're throwing from within a catch block or not.ack_inc

1 Answers

2
votes

You generally use throw where you can, i.e. in async functions or then callbacks, because it is simpler and therefore easier to read. return Promise.reject(…) does work but is lengthy.