4 ms·
I am stumbling over this: > Just remember: any code that might throw synchronously is a good candidate for a nearly-impossible-to-debug swallowed error somewhe
by janfoeh 11y ago
I am stumbling over this:
> Just remember: any code that might throw synchronously is a good candidate for a nearly-impossible-to-debug swallowed error somewhere down the line.
Why would a synchronously thrown error be swallowed, and why would I not just `try { } catch` here?
- nolanl 11y agonaivePromiseAPI() { 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.