Home > Net >  is it good practice to use try inside try block to catch different errors? - JavaScript
is it good practice to use try inside try block to catch different errors? - JavaScript

Time:08-30

I am using try catch inside try block to print relative message or get to know in which method error happened.

code snippet

  for (const searchUrl of savedSearchUrls) {
    console.log("here");
    // function will get all the links of profiles in saved search url
    try {
      const links = await scrapeFromurl(browser, searchUrl);
      try {
        saveToDatabase(links);
      } catch (e) {
        handleError(e, "eror while saving to database");
      }
    } catch (err) {
      handleError(err, "error in scrapeFromurl()");
    }
  }

I have searched on google but couldn't find related topic.

what are the other ways to accomplish similar things? what are the best practice to handle this type of situation.

CodePudding user response:

I would suggest using only one try catch block and specific error instances for each method, then in catch block you can simply check which method throws an error by using instanceof operator

class ScrapeError extends Error {
  message = "error in scrapeFromurl()"
}

class DBError extends Error {
  message = "eror while saving to database"
}

async function scrapeFromurl() {
  throw new ScrapeError();
}

async function saveToDatabase(links) {
  throw new DBError();
}

async function main() {
  try {
    const links = await scrapeFromurl();
    await saveToDatabase(links);
  } catch (e) {
  
    if (e instanceof ScrapeError) {
      console.log('scrape', e);
    }
    
    if (e instanceof DBError) {
      console.log('dberror', e);
    }
    
  }
}

main();

CodePudding user response:

In asyncronous scripts you can use domains for error handling. And trycatch in trycatch can be treated like domain in domain, which is pointless. Moreover, programmers always tend to prevent the code from growing horizontally like this

{
  ...
  {
    ...
    {
      ... (and so on)
      {
      }
    }
  }
}

So it is a really bad idea. I can keep on telling drawbacks of this approach, but not going to. Just use one trycatch with switchcase inside to handle all errors

  • Related