I have found several approaches to a clean error handling with async/await.
Some propose:
- handling error immediately on promise with
.catch()
(but it mixes up Promise and await syntaxes) - having promises return
[data, err]
instead of throwing (but it uglifies code with error checks) - creating errors that inherit Error object and match on
instanceof
in thecatch
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.