未捕获节点获取 HTTP 错误

node-fetch HTTP Errors not being caught

我在捕获 nodejs 获取异常时遇到了一些问题 我期待发生的是:

然而,打印到控制台的错误是:

Cannot connect to Server. Check you are using the correct IP Address and the server is running.
FetchError: request to http://localhost:3689/api/outputs failed, reason: connect ECONNREFUSED 127.0.0.1:3689

这意味着我抛出的错误没有被捕获,一些默认的获取错误被捕获,并且 CheckResponseStatus 没有被 运行.

我的代码如下

节点获取 HTTP 请求:

async function getStatus(serverip,serverport){
  return await fetch(`http://${serverip}:${serverport}/api/outputs`)
  .then(this.checkResponseStatus)
  .then(res => res.json())
  .catch((err) => this.ServerError(err));
}

检查响应状态函数:

checkResponseStatus(res) {
  if(res.ok){
      return res
  } 
  //will add elseif's here for different HTTP errors
  else {
      throw new Error(`The HTTP status of the response: ${res.status} (${res.statusText})`);
  }
}

服务器错误函数:

ServerError(err){
  console.log('Cannot connect to Server. Check you are using the correct IP Address and the server is running.');
  console.log(err);
}

感谢您的任何建议或帮助。

如果fetch无法连接到远程服务器,它将reject。在您的代码中,永远不会调用 checkResponseStatus 因为 fetch 永远无法获得响应;前两个 .then 块被跳过,因为 fetch 被拒绝,所以执行直接进入 .catch 块。

如果您希望网络错误 运行 到 checkResponseStatus,您可以在第一个 .then 之前添加第二个 .catch 并将错误格式化为“响应” :

fetch(`http://${serverip}:${serverport}/api/outputs`)
  .catch(err => {
    // return a mock failed response for checkResponseStatus to handle
    return {
      ok: false,
      status: -1,
      statusText: 'Network Failure',
    };
  })
  .then(this.checkResponseStatus)
  .then(res => res.json())
  .catch((err) => this.ServerError(err));

但是,我相信您的代码目前 运行 符合我的预期 - 跳过网络故障 checkResponseStatus,这是有道理的,因为没有真正的响应需要检查。