3 ms·
naivePromiseAPI() { if (foo) { throw new Error('this will get swallowed!'); } return somePromise(); } Instead you want this: cleverPromi
by nolanl 11y ago
naivePromiseAPI() {
if (foo) {
throw new Error('this will get swallowed!');
}
return somePromise();
}
Instead you want this:
cleverPromiseAPI() {
return Promise.resolve().then(function () {
if (foo) {
throw new Error('this won't get swallowed!');
}
return somePromise();
});
}
Because if the client of the API does something like this:
$('.my-button').on('click', function () {
cleverPromiseAPI().catch(console.log.bind(console));
});
Then the client might expect the error to get console.logged, but actually it won't in the naive case. That's because the error was thrown synchronously and thus bubbled up to the click handler, instead of being caught inside of the promise chain.
- janfoeh 11y agoAh, I get it now, thanks! I missed the part about doing that for synchronous code in promise-returning APIs. I had a moment of stupidity and first somehow understood that to be a general suggestion for error handling.