如何在 React with Fetch 中处理 'ECONNREFUSED'?

How to handle 'ECONNREFUSED' in React with Fetch?

我在 React 中有以下与第三方交互的代码 api。当目标 PC 上的 Avaya One-X 客户端未 运行ning 时,我在控制台中收到错误连接被拒绝的消息,这是正常的。问题是代码每 5 秒设置为 运行,只要 one-x 客户端不是 运行ning,控制台就会充满这些错误。

我怎样才能更好地处理这个问题?没有记录那么多次就好了。

  fetchData = (url) => {
    return new Promise((res, rej) => {
      fetch(url)
        .then((r) => r.text())
        .then((text) => {
          res(text);
        })
        .catch((e) => rej(e));
    });
  };

  getLogs = async () => {
    try {
      const { user } = this.props.auth;
      const regxmlPromise = this.fetchData(
        `http://127.0.0.1:60000/onexagent/api/registerclient?name=${user.id}`
      );
      const clientIdPromise = this.fetchData(
        `/api/avaya/${user.id}/getclientid/`
      );

      
      const resolves = await Promise.all([regxmlPromise, clientIdPromise]);

      const [registration, clientId] = resolves || [];

      const nextNotification = await this.fetchData(
        `http://127.0.0.1:60000/onexagent/api/nextnotification?clientid=${clientId}`
      );

      if (registration) {
        const regxml = new XMLParser().parseFromString(registration);
        if (regxml.attributes.ResponseCode === "0") {
          axios.post(`/api/avaya/${user.id}/register/`, regxml);
          console.log("ClientId sent!");
        }
      }

      if (nextNotification) {
        const xml = new XMLParser().parseFromString(nextNotification);
        if (
          xml.children[0].name === "VoiceInteractionCreated" ||
          xml.children[0].name === "VoiceInteractionMissed" ||
          xml.children[0].name === "VoiceInteractionTerminated"
        ) {
          console.log(xml);
          console.log(xml.children[0].name);
          axios.post(`/api/avaya/${user.id}/logcalls/`, xml);
        }
      }
    } catch (error) {
      console.log(error);
    }
  };

  timer = (time) => {
    const date = new Date(time);
    return `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
  };

  componentDidMount() {
    this.getLogs();
    this.callsInterval = setInterval(this.getLogs, 5000);
  }

  componentWillUnmount() {
    clearInterval(this.callsInterval);
  }

为了让事情更清楚,这是控制台的屏幕截图。我收到拒绝连接的获取错误以及我捕获并记录的实际错误。因此,即使我捕获到错误并且什么都不做,无论如何我仍然会在控制台中记录连接被拒绝。

一件有趣的事情是,如果我使用 fetch-node,我会得到不同的行为和错误消息。节点的错误是一个对象并且具有不同的道具。在 React 中,如果我 console.log 获取请求错误,我只会得到“TypeError: Failed to fetch”

您可以进行指数退避:https://en.wikipedia.org/wiki/Exponential_backoff

基本上只是增加每次失败尝试之间的时间。很常见的做法。

如果你只是不想看到它,你可以只捕捉它而不记录它。

因此,如果您只是想隐藏网络错误消息,您可以单击 Chrome 中的齿轮箱并点击“隐藏网络”。显然在 Chrome 中,即使您捕获到网络错误,它们仍然会冒泡到控制台,除非您 select 这样做。我用的是 Firefox,一开始没看出问题。

可以在此处找到更多信息:Catching net::ERR_NAME_NOT_RESOLVED for fixing bad img links