【问题标题】:Axios error status code UnhandledPromiseRejectionWarningaxios 错误状态码 UnhandledPromiseRejectionWarning
【发布时间】:2019-12-13 05:05:51
【问题描述】:

使用 axios,我正在向多个链接发出 GET 请求以测试它们是否是断开的链接。如果 GET 请求返回错误,我想将此错误记录到控制台并使用套接字将其发送到客户端。但是,在 一些 链接(不是全部)上,我得到一个 UnhandledPromiseRejectionWarning。

// check if the link is dead
axios.get(linkHref, {
   auth: {
     username: USERNAME,
     password: PASSWORD
   }
})
.then( (response) => {
  if (response.status != 200) {
    resultData = {
      text: linkText,
      url: linkHref,
      statusCode: String(response.status)
    }
    console.log(resultData);
    io.sockets.emit("result", resultData); // send link to client-side
  }
})
.catch( (error) => {
if (error) {
    resultData = {
      text: linkText,
      url: linkHref,
      statusCode: String(error.response.status) // this is where the error is
   }
   console.log(resultData);
   io.sockets.emit("result", resultData); // send link to client-side
  }
});

我希望它能正常工作并返回错误的状态代码,但有时我会收到 UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'status' of undefined 错误。但是使用.catch 中的 if 语句,我正在检查以确保 is 有一个错误并且它不是未定义的,所以我不明白为什么会出现这个错误。

编辑:另外,当我在我的 Mac 上运行它而不是在 Windows 上运行它时,它可以工作(不会向我显示那个错误)......为什么?

【问题讨论】:

    标签: javascript node.js express axios


    【解决方案1】:

    TypeError: Cannot read property 'status' of undefined error.response 上的response 属性未定义,例如error = { response: undefined }。因此,在其上引用任何属性都会引发错误。 error.response[property]

    另外对于失败/挂起的http请求,error参数是不同的。查看此要点axios-catch-error。对于这种情况,error 参数将具有不同的属性。

    【讨论】:

      【解决方案2】:

      你可以通过验证是否在 if else 条件下获取错误对象的响应属性来检查

      .catch( (error) => {
      if (error.response) {
         //rest of the code...
        }
      });
      

      【讨论】:

        猜你喜欢
        • 2018-07-31
        • 1970-01-01
        • 1970-01-01
        • 2022-12-11
        • 2021-09-28
        • 2019-08-15
        • 1970-01-01
        • 2020-04-12
        • 2021-01-12
        相关资源
        最近更新 更多