Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it anti-pattern to run asynchronous callbacks in catch blocks?

Is it an anti-pattern to run asynchronous callbacks in error catching like this?

await something()
   .catch(async (err) => {
      console.error(err);
      await otherStuff();
   });

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If your intent is to have that whole expression there never reject – that is, to avoid the need for

try {
  await something()
   .catch(async (err) => {
      // ...
} catch(e) {
  // handle
}

Then what you’re doing right now isn’t safe if there’s any chance of the otherStuff call rejecting. If otherStuff might reject, then you should make sure to catch possible errors it throws, eg

await something()
   .catch(async (err) => {
      console.error(err);
      await otherStuff();
   })
   .catch(handleOtherStuffErrors)

Though having an async function with only a single await isn’t that useful – consider instead just returning the Promise:

await something()
   .catch((err) => {
      console.error(err);
      return otherStuff();
   })
   .catch(handleOtherStuffErrors)

Chaining catches like that is pretty odd, but it’s not impossible that that’s what one’s logic requires, so don’t make a blanket statement about whether it’s inherently bad.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading