在 React、JavaScript 中捕获 504(网关超时)错误

苏雷什·波卡雷尔

我有一个有效的 API 可以从服务器获取项目,如下所示。我正在使用 React 来使用这些数据。现在,我想捕获所有以 5__ 开头的服务器错误,并显示一条消息,如“未连接到互联网”或类似内容。

 export const GetItems = (operand, searchValue) => {
      const trimmedValue = searchValue.trim();
      let combinedResults;
      // make 2 API calls to search on both item_name and code;
      // then combine them;
      // there is no API method to do this, that I could find
      return getItemsByName(operand, trimmedValue)
      .then(result => (
        (combinedResults = [].concat(result))
      ))
      .then(() => getItemsByCode(operand, trimmedValue))
      .then(result => (
        (combinedResults = combinedResults.concat(result))
      ));
    };

目前,我需要查看控制台以检查连接是否存在问题。

504 网关超时错误


根据@Dane 的要求更新

const getItemsByCode = (operand, searchValue) => (
  FetchToJson(BuildCodeSearchUrl(operand, searchValue))
);

它只是调用一个方法来构建 URL。您可以认为一切正常,如果有连接,就会得到响应。

丹麦人

使用catch()

return getItemsByName(operand, trimmedValue)
      .then(result => (
        (combinedResults = [].concat(result))
      ))
      .then(() => getItemsByCode(operand, trimmedValue))
      .then(result => (
        (combinedResults = combinedResults.concat(result))
      ))
      .catch((error) => {
        if (error.response) { // if there is response, it means its not a 50x, but 4xx

        } else {   // gets activated on 50x errors, since no response from server
          // do whatever you want here :)
        }            
      });

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章