我如何很好地管理try catch?

How do I well manage try catch?

努力管理大量 try catch。

代码库中有很多try catch。如果我忘记添加 try catch,它会 returns 一条不明确的错误消息或事件 returns。但是,如果我在每个地方都添加 try catch,它就像一团糟......

怎么才能搞好try catch?

获取帐户数据的操作

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

正在从 API

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

如何处理错误取决于您。在这里,我选择了 alert 用户。如果这是一个生产应用程序,我可能会重试该请求,或者使用 toast 通知告诉用户重试(并且可能在重试之前重新加载)。

<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>

您的 updateAccountBalance 可以有一个 try-catch 模式,捕捉任何错误,例如,打印您想要的信息。例如,假设您的 fetchBalance 函数 returns 出现以下错误:

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

然后让我们定义另一个函数来做一些不同的错误:

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

如果您用一个 try-catch 包围您的 updateAccountBalance 函数,例如:

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

这只是为了记录信息的目的,如果你想处理每个错误并执行不同的任务,我认为第一种方法是最好的,对你想处理的每个错误使用 flatten try-catch(但是避免在收到一个错误后抛出另一个错误)。