Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 139893

Javascript async/await error handling: match throwing function in catch block

$
0
0

I have found several approaches to a clean error handling with async/await.

Some propose:

  1. handling error immediately on promise with .catch() (but it mixes up Promise and await syntaxes)
  2. having promises return [data, err] instead of throwing (but it uglifies code with error checks)
  3. creating errors that inherit Error object and match on instanceof in the catch block (this one is nice and fine, but requires to define as many classes).

Before I implement option 3 in all my code, I am wondering why I can't find the following anywhere. If my AsyncFunction is not about to throw different errors, why not just match the function directly?

async function a() {}
async function b() {
  throw b;
}
(async () => {
  try {
    await a();
    await b();
  }
  catch (err) {
    switch (err) {
    case a: console.log('a threw'); break;
    case b: console.log('b threw'); break; // this one is executed
    }
  }
}) ()

There may be obvious reasons why we should never do that, but I'm stuck there.


Viewing all articles
Browse latest Browse all 139893

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>