试着抓。即使没有失败,try语句也会出现错误

时间:2019-05-11 17:25:47

标签: javascript error-handling try-catch

我正在尝试使用PATCH方法使用Fetch API在javascript上实现try / catch。在大多数情况下,获取成功时,我会收到400(错误请求)错误,但我不知道为什么,我想知道是否忘记在try语句内添加if语句来检查响应状态,然后再跳转到捕获语句。我还创建了一个名为retry()的函数,以不允许用户进行超过3次失败的调用。 如果我失败了,我将看不到numberOfRetries日志已更新。

const retry = async (callback, numberOfRetries) =>
  await callback(numberOfRetries)

export const updateValue = async (name, active, numberOfRetries = 0) => {
  try {
    await fetch(`${apiUrl}/device/${name}?active=${active}`, {
      method: 'PATCH',
      headers: {
        Accept: 'application/json',
        'Content-type': 'application/json; charset=UTF-8'
      },
      body: JSON.stringify({
        name,
        active
      })
    })
    console.log('ok')
  } catch (error) {
    if (numberOfRetries >= 2) {
      return
    }
    console.log(`retry number ${numberOfRetries}`)
    return await retry(updateValue, ++numberOfRetries)
  }
}

Console screenshot

enter image description here

1 个答案:

答案 0 :(得分:1)

  

获取成功后,我收到一个400(错误请求)错误,我不知道为什么,它跳到catch语句中。

否,catch块未运行。您在devtools日志中看到的错误是因为网络请求失败,并显示HTTP错误代码。您可以disable the log messages in the console options

关于为什么获得400代码的原因,您必须检查服务器端代码-这表明您在执行请求时出错。

  

我想知道是否忘记在try语句中添加if语句来检查响应状态

是的,您也忘记了这一点。您应该检查.ok property of the response

export const updateValue = async (name, active, numberOfRetries = 0) => {
  try {
    const response = await fetch(`${apiUrl}/device/${name}?active=${active}`, {
//  ^^^^^^^^^^^^^^
      method: 'PATCH',
      headers: {
        Accept: 'application/json',
        'Content-type': 'application/json; charset=UTF-8'
      },
      body: JSON.stringify({
        name,
        active
      })
    })
    if (response.ok) {
//  ^^^^^^^^^^^^^^^^
      console.log('ok')
      // console.log(await response.text()) or something
    } else {
      throw new Error("HTTP Error "+response.status);
    }
  } catch (error) {
    if (numberOfRetries >= 2) {
      return
//    ^^^^^^ should be `throw error` instead of returning undefined?
    }
    console.log(`retry number ${numberOfRetries}`)
    return updateValue(name, active, ++numberOfRetries)
//                     ^^^^^^^^^^^^^ pretty surely you'll want to pass through the arguments
  }
}