处理错误捕获正确然后呢?

我只是困惑做这件事的正确方法是什么,我已经在反应中获取了这样的代码:

  fetch(
    `api_url`,
  )
    .then(response => response.json())
    .then(
      successResponse => {
       ...
      },
      errorResponse => {
       ...
      }
    )

还是我应该在下面使用这个?我应该放在哪里。

  fetch(
    `api_url`,
  )
    .then(response => response.json())
     // put .catch() here?
    .then(
      successResponse => {
       ...
      }
    )
    .catch(errorResponse => {
      ...
     }
    )

两者之间有区别吗?我喜欢第一个,这两个捕获错误是否不同?

评论
  • 逗你玩~
    逗你玩~ 回复

    There's nothing wrong with your first attempt, but you can throw an error if you're worried about about the response.json() call failing.

    fetch(`api_url`)
    .then((response) => {
      if (response.ok) return response.json()
      else throw new Error('Could not fetch')
    })
    .then((successResponse) => {
      ...
    })
    .catch((errorResponse) => {
      console.log(errorResponse)
    })