Javascript 抓取时正确处理错误捕获?

Javascript 抓取时正确处理错误捕获?,javascript,Javascript,我只是不知道该怎么做,我在react中获取了如下代码: fetch( `api_url`, ) .then(response => response.json()) .then( successResponse => { ... }, errorResponse => { ... } ) 或者我应该用下面这个来代替?我该把它放在哪里?接住 fetch(

我只是不知道该怎么做,我在react中获取了如下代码:

  fetch(
    `api_url`,
  )
    .then(response => response.json())
    .then(
      successResponse => {
       ...
      },
      errorResponse => {
       ...
      }
    )
或者我应该用下面这个来代替?我该把它放在哪里?接住

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

这两者有区别吗?我喜欢第一个,两个catch错误不同吗?

如果您担心
响应.json()
调用失败,只需在第一个
调用中抛出一个新错误即可。然后
调用

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

当承诺被拒绝时,将调用
.catch
。对于
.json()
函数,它返回另一个承诺,因此可以使用
.catch
函数。只有当您得到无效的json对象时,它才会拒绝。如果您有一些特定于响应代码的处理,则必须使用第一个示例。