是否可以根据是否停止执行try块并开始执行catch块的条件在try catch块中引发Exception?

时间:2020-08-21 15:49:55

标签: javascript exception try-catch

示例

try {
      let items = JSON.parse(localStorage.getItem('items'))
      if(items.length === 0){
          throw new Exception()    
      }
      // other code
      fetch('http://localhost:9004/merge-items').then(...)
}catch(e){
      console.error(e)
      fetch('http://localhost:9004/load-items').then(...)
}

我在if块内抛出异常,因为我需要编写与catch块内相似的代码

try {
      let items = JSON.parse(localStorage.getItem('items'))
      if(items.length === 0){
           fetch('http://localhost:9004/load-items').then(...)   // The same code
      }
      // other code
      fetch('http://localhost:9004/merge-items').then(...)
}catch(e){
      console.error(e)
      fetch('http://localhost:9004/load-items').then(...) // The same code
}

1 个答案:

答案 0 :(得分:0)

如果您仅询问是否可以,则问“否”,那不是很好。

您可以将异常视为您不希望看到的东西,但是您可以预测到。您期望在您的代码中,有时(在一开始?)您的本地存储项目可能为空。

所以,更好:

const loadItems = () => {
  fetch('http://localhost:9004/load-items').then(...)   // The same code
}

try {
  let items = JSON.parse(localStorage.getItem('items'))
  if (items.length === 0) {
    loadItems();
  }
  // other code
  fetch('http://localhost:9004/merge-items').then(...)
} catch (e) {
  console.error(e)
  loadItems();
}
相关问题