Home > other >  How do I well manage try catch?
How do I well manage try catch?

Time:04-20

Struggling to manage lots of try catch.

There are lots of try catch in the code base. If I forget to add try catch, it returns an unclear error message or event nothing returns. But if I add try catch every where, it kind like a mess...

How could I manage well try catch?

Actions for get an account data

async updateAccountBalance() {
  try {
    const newBalance = await fetchBalance(accountName)
  } catch (err) {
    throw new Error(err)
  }
  ...another try catch
  return result
}

Fetching data from API

async fetchBalance(accountName) {
  try {
    const res = await request(url, accountName)
  } catch (err) {
    throw new Error(err)
  }
}

CodePudding user response:

However you handle your errors is up to you. Here, I've chosen to alert the user. If this were a production application, I'd likely retry the request, or use a toast notification telling the user to retry (and maybe reload before retrying).

<button onclick="myFunction()">Click me</button>

<script>
    const randomlyThrows = () => {
    const val = Math.round(Math.random() * 1);
    if (val) throw new Error('oops');
};

const myFunction = () => {
    try {
        randomlyThrows();
    } catch (error) {
        alert(`Error: ${error.message}`);
    }
};
</script>

CodePudding user response:

Your updateAccountBalance can have a single try-catch pattern, catching any error and, for example, printing the information you want. For example, lets say your fetchBalance function returns the following error:

async fetchBalance(accountName) {
  try {
    const res = await request(url, accountName)
  } catch (err) {
    throw new Error("User not found")
  }
}

And lets define another function that does something else with a different error:

async doSome(accountName) {
  try {
    const res = await anotherMethod(accountName)
  } catch (err) {
    throw new Error("Different error")
  }
}

If you surround your updateAccountBalance function with a single try-catch like:

async updateAccountBalance() {
  try {
    const newBalance = await fetchBalance(accountName)
    const some = await doSome(accountName);
    ...
    return result
  } catch (err) {
    // Print the error for example
  }
}

This is only for logging information purposes, if you want to handle each error and perform different tasks, I think the first approach is the best, using flatten try-catch for each error you want to handle (but avoid throwing another error after receiving one).

  • Related